A little gotcha with Azure PowerShell Functions

Recently, I had a great use case for using the PowerShell support within Azure Functions.  During development, I encountered a weird behaviour on the error handling side.  In this short blog, I want to share this experience with you.  Hopefully, it can save you some troubleshooting time!

Starting point

My initial function looked like this, based on the samples in the developer guide.  Even though my code was not working correctly, the Azure Function kept on returning an HTTP 200.  I would have expected an internal server error.

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# My code that was not working correctly

# Return output HTTP response
$status = [HttpStatusCode]::OK
$body = "RESOURCETYPE_NOT_CONFIGURED"

Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = $status
    Body = $body
})

Adding try/catch

My next attempt, was to add a try catch.  In case of an exception, I return an internal server error that includes the exception detail.  However, still no error is returned.  Despite all my efforts, I kept on receiving an HTTP 200 when invoking the PowerShell Function.

try
{
   # My code that was not working correctly
}
catch
{
   $body = $_.Exception.Message
   $status = [HttpStatusCode]::InternalServerError
}

The solution

After some Googling around, this blog helped me out.  PowerShell has terminating and non-terminating errors.  A catch block is only handling terminating errors.  In my use case, I want to handle every error.  This can be done by adding the following statement to your script.  This tells PowerShell to treat every error as a terminating one.

$ErrorActionPreference = "Stop"

From now on, I received clear error messages with HTTP status 500.

Conclusion

I used this error handling statement already many times before, but I forgot to use it within the context of Azure Functions.  Azure Functions supports multiple languages, each of them come with their own specifics.  This is one of them, that I won’t forget anymore!

Cheers
Toon

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s