powershellwrapper icon indicating copy to clipboard operation
powershellwrapper copied to clipboard

Add setting for re-throwing exceptions instead of Write-Error inside try-catch

Open Spacetornado opened this issue 5 years ago • 2 comments

Is your feature request related to a problem? Please describe. We've written a lot of PowerShell functions that use the functions in this module, to avoid re-writing a lot of duplicate code. When requests are successful, this works great. But when there's an exception returned by the IT Glue API, it's caught in the try/catch/finally blocks inside the powershellwrapper functions & written to Write-Error, so we can't catch it in our functions/scripts.

Example from FlexibleAssets.ps1:

try {

... Invoke-RestMethod ... -headers $ITGlue_Headers

} catch {

Write-Error $_

}

Describe the solution you'd like It would be great if there was a global setting/preference (in config.psd1) -- something like "ReThrowExceptions" -- which changes the behavior of all the functions so instead of just doing Write-Error $_ in the catch { } block, they do throw $_ instead. That way the exception can be handled by the function/script that's calling the ITGlueAPI function. Something like:

try {

Invoke-RestMethod ... -headers $ITGlue_Headers ...

}

catch {

if ($ReThrowExceptions) { throw $_.Exception }

else { Write-Error $_ }

}

Describe alternatives you've considered There's the built-in variable $Error that stores all exceptions, with $Error[0] always being the latest one. But using that would require keeping track of the number of items in that ArrayList, and checking its Count after every ITGlueAPI function call to see if it has increased. That's possible but not nearly as ideal as using try/catch.

Spacetornado avatar Jul 26 '19 18:07 Spacetornado

To add a little more context to this, we wrote a fairly complex .PS1 script that uses the ITGlueAPI module to synchronize our configuration items in ConnectWise Manage with flexible assets in IT Glue. This script is run via scheduled task on a recurring basis, so we're not running it interactively and looking at the output. Sometimes there's an issue with the sync process and the IT Glue API returns an error. Because that error is just written to the error output stream, our script can't catch it and handle it gracefully. So we have to go run the script manually and read the error in the output. It would be ideal if we could catch the errors (exceptions) and email them to ourselves, and also handle them automatically in the script, based on the error text.

Spacetornado avatar Jul 26 '19 18:07 Spacetornado

@Spacetornado You can ask PowerShell to treat errors as exceptions by adding the parameter -ErrorAction Stop or by setting $ErrorActionPreference = $true. For example:

try {
    Get-ITGlueConfigurations -ErrorAction Stop
} catch {
    # handle both errors and exceptions here
}

davidhaymond avatar Dec 07 '22 23:12 davidhaymond