Chapter 11. A template for handling and reporting errors

 

Will Steele

Writing programs that work when everything goes as expected is a good start. Making your programs behave properly when encountering unexpected conditions is where it really gets challenging.

Marijn Haverbeke
Eloquent JavaScript: A Modern Introduction to Programming

Efficient, predictable error handling has been at the core of PowerShell’s design since its earliest days and has allowed scripters to design robust automation solutions with minimal effort. In small scripts a balanced combination of common parameters, the use of Write-Error, or perhaps Write-Warning, and some well-placed if/then statements generally prove to be enough for most scripter’s daily automation problems. As the size and complexity of my scripts have grown, though, so, too, has my need for a hands-off integration of error handling. With these larger scripts my focus on problem management has dwindled relative to how much the amount of time and energy spent on properly automating the task has increased. In this chapter we’ll explore an approach I developed to automatically and precisely report errors using a reusable script template.

Using preference variables: $ErrorActionPreference

Using structured error handling: try/catch/finally

Using $Error and InvocationInfo objects

Handling custom business-logic errors with throw and try

Final template

Summary

About the author

sitemap