我正在使用PowerShell returns human-readable errors as a json object in the response body发生错误时使用API。但是,当我尝试在异常中找到json主体时,我可以看到错误,基础System.Net.WebException
和更深层System.Net.HttpWebResponse
,但我无处可找到他们所指的实际主体。这是可以访问的吗?
例如,这是一个有效的API调用:
Invoke-RestMethod -Method Get -Headers @{Authorization="Token token=$YourTokenHere";"Content-type"="application/json"} -Uri "https://mydomain.pagerduty.com/api/v1/users/ABCDEF" -Body @{offset=0;limit=100}
如果您随后更改了URI末尾的用户ID,则会失败,并且您收到此错误:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:1 char:1
+ Invoke-RestMethod -Method Get -Headers @{Authorization="Token token=b ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
如果我执行以下操作并转换为json以便于查看子属性,我可以深入查看错误以查看基础错误和响应:
$Error[0].Exception.Response | ConvertTo-Json
但无论我如何梳理这些错误,我似乎无法找到json的身体。它可能在哪里,或者我如何捕获它?如果我试一试,我似乎有相同的结果。
答案 0 :(得分:1)
您可以阅读响应流,以便获得响应的正文。例如:
try {
Invoke-RestMethod -Method Get -Headers @{Authorization="Token token=$YourTokenHere";"Content-type"="application/json"} -Uri "https://mydomain.pagerduty.com/api/v1/users/ABCDEF" -Body @{offset=0;limit=100}
} catch {
$stream = New-Object System.IO.StreamReader $_.Exception.Response.GetResponseStream()
$json = $stream.ReadToEnd()
$stream.Dispose()
$json
}
输出:
{"error":{"message":"Account Not Found","code":2007}}