I’ve implemented some crazy ways of error handling over the years. I wanted to quickly show and explain what I currently put in my Catch block for most of my PowerShell functions. Here is a typical catch statement in one of my functions:
Write-Warning “Unexpected error occurred while executing $((Get-PSCallStack).Command) with exception: $($_.Exception.Message)”
Write-Warning “Command: `’$($_.InvocationInfo.Line.Trim())`'”
I’ll usually have some error handling for specific conditions such as unexpected object state/data which usually results in a return from the function, so if we actually hit a catch block, something is REALLY not right. If you have a script with several hundred lines, a dozen functions and you suddenly hit an unexpected error, it can be tedious to figure out where the error actually came from. In the past, I’ve gone back to my scripts, added a bunch of ‘Write-Host “Just passed this section of code”’ or similar debug lines. I very rarely have to perform this level of debugging with my current catch block reporting.
Let’s break down what is happening here and take a look at some sample output. Get-PSCallStack was designed to be used with the PowerShell debugger. It works inside scripts and functions. Here we are looking at the first item in the call stack, getting the command and displaying the exception message. This is the function name, or script name if you’re not in a function. The second line takes a look at the InvocationInfo property of our exception. The InvocationInfo has a property called Line which contains the text from the line of the script or function that generated the error. Another option in this scenario instead of collecting the Line property is to collect the MyCommand.Name property which will return the cmdlet that generated the error. Given the context of the caller and the line or name of the cmdlet, it will be easier to determine where the error is occurring.
Seen below, we have some sample information from a function called Get-FileInformation, which is throwing an error when calling the Test-Path cmdlet with a null value.
In the output, we have a lot more information about what caused the error, and where we should start looking for the problem.