简体   繁体   中英

Can't find expected json body in System.Net.WebException

I'm working with an API via PowerShell that returns human-readable errors as a json object in the response body when an error occurs. However, when I attempt to find that json body in an exception, I can see the error, the underlying System.Net.WebException and the further underlying System.Net.HttpWebResponse , but nowhere can I find the actual body they're referring to. Is this something that is accessible?

For example, here is a valid API call that would work:

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}

If you then change the user ID at the end of the URI, it fails and you get this error:

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

I can dive down in to the error to see the underlying error and the response if I do the following and convert to json for easy viewing of subproperties: $Error[0].Exception.Response | ConvertTo-Json $Error[0].Exception.Response | ConvertTo-Json

But no matter how I comb through these errors, I can't seem to find the json body. Where might it be, or how can I capture it? I seem to have the same result if I do a try/catch.

You could read the responsestream so you can get the body of the response. Ex:

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
}

Output:

{"error":{"message":"Account Not Found","code":2007}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM