Working with HTTP errors in PowerShell

PowerShell is a great language to query REST APIs. When I call a REST API, I usually expect things to go well, but sometimes it doesn’t. So, how should I handle HTTP errors like 404, 403, and so on?

When invoking REST API methods, I use PowerShell’s ‘Invoke-RestMethod‘ cmdlet.
When I call a REST method with ‘Invoke-RestMethod,’ it returns a string containing the content returned by the REST method.
If the REST method returns a valid result, everything is okay. If the REST method returns an error, then ‘Invoke-RestMethod‘ returns nothing.
So, how do we inspect HTTP errors with ‘Invoke-RestMethod‘? There are two ways to do this: either through the ‘ErrorVariable’ or using the ‘SkipErrorCheck’ parameter.
I will explain the two approaches in this blog post.

Approach 1: using the ‘ErrorVariable.’

The following code calls a REST method that returns HTTP error 404. The ‘ErrorVariable‘ parameter stores the error object in a variable called ‘myerror.’

We can then use the ‘myerror‘ to get things like the status code, request headers, and response headers.

Invoke-RestMethod https://rasmusg.net/http404 -ErrorVariable myerror
 
# Get HTTP status code (enum HttpStatusCode):
# Status code name:
$myerror.ErrorRecord.Exception.Response.StatusCode
# Status code number
[int]$myerror.ErrorRecord.Exception.Response.StatusCode
 
# Get response headers
$myerror.ErrorRecord.Exception.Response.Headers
 
# Get request message
$myerror.ErrorRecord.Exception.Response.RequestMessage

Approach 2: Using the ‘SkipHttpErrorCheck’ parameter

The following code shows the use of the ‘SkipErrorCheck‘ parameter. Using this parameter, ‘Invoke-RestMethod’ will not check for any HTTP errors and return the response regardless. If you use this approach, it is good to use the ‘StatusCodeVariable’ and ‘HeadersVariable’ to store status code and header info, respectively. This way, you can validate status code and inspect response headers (e.g., to inspect an API Management request trace).

$response = Invoke-RestMethod https://rasmusg.net/error404 -ErrorVariable myerror -StatusCodeVariable mystatus -ResponseHeadersVariable myheaders -SkipHttpErrorCheck

Conclusion

This blog post shows you how to invoke REST API methods and retrieve error information.

It is also possible to implement the actual REST API using PowerShell. Check out my blog post about How to create a PowerShell Azure Function to see how you can use PowerShell to implement a REST API through Azure Functions.

Thanks for reading, and feel free to post a comment!

8