4

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?

1 Answer 1

8

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, cheers, just a note is that in my case $_.ErrorDetails.Message was null, so I didn't get anything from there, directly reading the response stream worked a treat though. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.