为什么在调用Invoke-RestMethod失败后,$_Exception没有内容?

问题描述 投票:-1回答:1

当我在PowerShell中调用Invoke-RestMethod时,我试图捕获错误响应。代码到了捕获块,但$_Exception属性总是空的。

我在另一个问题上找到了这段代码,但是它没有工作。这些变量中从来没有任何数据。

    catch [System.Net.WebException] {   
         $respStream = $_.Exception.Response.GetResponseStream()
         $reader = New-Object System.IO.StreamReader($respStream)
         $respBody = $reader.ReadToEnd() | ConvertFrom-Json
         Write-Host "Response is $respBody." #$respBody is empty
         $_Exception #$_Exception is empty
    }

我像这样调用我的请求。$response = Invoke-RestMethod -Uri "$root_url$url" -Method $method -Headers $headers -Body $json

如果我没有trycatch, 失败的响应(ex 400)JSON会被输出到控制台, 所以我知道PowerShell看到了它, 但我不知道当我试图在捕获块中访问它时, 它把它放在哪里.

有人知道我做错了什么吗?

powershell
1个回答
0
投票

我发现了一些工作。添加 $respStream.Position = 0 解决了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.