Help with Error Handling – How to cut down on verbosity of error output with a function that is several-functions-deep?

I guess today is Error Handling Day 🙂

Now that I have a pretty deep library of scripts/functions, error handling is becoming more and more important/problematic. I’m trying to figure out a standardized and less verbose way for handling errors that occur on a function that’s a child of a child of a child of a parent function. Here’s an example of what I’m messing with:

https://gist.github.com/pldmgg/9434e09384d8280e0d0fa395cfa89c4c

Ideally, when I run Test-Func, I just want Test-Func’s catch block to ONLY spit out error information that says:

  • That the New-VagrantBox function failed on ErrorHandlingTest.ps1 line #3
  • All errors that the New-Vagrant function has EXCEPT errors that I’ve specifically suppressed with ‘-ErrorAction SilentlyContinue’
  • That the Install-Program function failed on ErrorHandlingTest.ps1 line #26
  • All errors that the Install-Program function has EXCEPT errors that I’ve specifically suppressed with ‘-ErrorAction SilentlyContinue’
  • That the Install-ChocolateyCmdLine function failed on ErrorHandlingTest.ps1 line #73
  • All errors that the Install-ChocolateyCmdLine function has EXCEPT errors that I’ve specifically suppressed with ‘-ErrorAction SilentlyContinue’
  • I only want to see that there was a ‘divide by zero’ error ONE time

The problem with the way I currently have it written is that tells me about the ‘divide by zero’ error 4 times and it tells me about errors that I’ve specifically suppressed with ‘-ErrorAction SilentlyContinue’ within each function (specificially the Get-Command statements in the if blocks).

Using ‘-ErrorAction Stop’ for lines 3, 26 and 73 doesn’t seem to cut down on the repetitiveness/verbosity either.

I have a suspicion that there’s no good way to get less repetitive Error output for this type of scenario…but I’m hoping I’m wrong 🙁

Thanks in advance for any advice/suggestions on better approaches to error handling for these types of situations!

SIDE NOTE:

I’m also not really sure if this pattern in my catch blocks is really the appropriate way of outputting the -ErrorVariable variable:

Write-Error $($ErrVar | Out-String) 

submitted by /u/fourierswager
[link] [comments]

Leave a Reply