So I'm calling a rest web service via powershell which responds with a 400 status code if you try to post data which has already been processed, along with the status code it also returns a JSON response in along the lines of:
{
"statusCode": 400,
"errorCode": "REQUEST_VALIDATION_ERROR",
"message": "validation failed",
"developerMessage": " MessageId-xxx already processed. No Need to process again."
}
So I try calling this with some powershell and receive the 400 status code and handle this using try/catch to get the exception, but there is no content in the response, I can get the response headers, status code, status message etc, but I cannot find a way to access the JSON response at all, here is the format of the powershell code I'm using:
$url = "https://example.com/webservice/status"
$cert = Get-ChildItem Cert:\CurrentUser\My\certthumbprintxxxxx
$headers = @{"tokenId" = "tokenxxxxx"}
$body =
@"
{
...
JSON data...
...
}
"@
try
{
$response = Invoke-WebRequest $url -Certificate $cert -Headers $headers -Method Post -Body $body
}
catch
{
$_.Exception.response
}
When I send $_.Exception.response to Get-Member I can see that there is no content property. How can I access the message in the response using powershell?
You can access the content message from ErrorDetails Property via $_.ErrorDetails.Message. It returns a string.
As an alternative you can also directly read the stream from WebResponse class using $_.Exception.Response.GetResponseStream() (as described here, I had to put the stream to position 0 again as it seems to already have been read by powershell)
$s = $_.Exception.Response.GetResponseStream()
$s.Position = 0;
$sr = New-Object System.IO.StreamReader($s)
$err = $sr.ReadToEnd()
$sr.Close()
$s.Close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With