Last active
May 19, 2022 09:54
-
-
Save fatherjack/5781f249d06fb41762b62207134d4c5b to your computer and use it in GitHub Desktop.
To find the Exception inheritence of an error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Show-ExceptionType { | |
<# | |
.SYNOPSIS | |
Function to give inheritence of exception types for error handling purposes | |
.DESCRIPTION | |
Take an error and returns all InnerException types for the Error object and the error message | |
.PARAMETER Exception | |
The error exception as it occurred in your script | |
.EXAMPLE | |
try { | |
10/0 | |
} | |
catch { | |
Show-ExceptionType -Exception $_.Exception | |
} | |
This example causes a Divide by zero error which is Exception type System.DivideByZeroException which is part of the System.Management.Automation.RuntimeException exceptions | |
Output is : | |
System.Management.Automation.RuntimeException - Attempted to divide by zero. | |
System.DivideByZeroException - Attempted to divide by zero. | |
.EXAMPLE | |
try { | |
10/0 | |
} | |
catch { | |
Show-ExceptionType -Exception $_.Exception -outputasobject | |
} | |
.NOTES | |
I didnt create this script but I am sorry to say that I cant recall the source either. | |
Thank you anonymous PowerShell person. | |
Script reproduced here as I often forget what I call it and where I save it and it might be useful to others | |
Updates | |
to change from write-host to write-output otherwise called functions cant consume the output | |
to include error message | |
to offer option to have string or object output | |
#> | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory = $true)] | |
[System.Exception] | |
$Exception, | |
# Whether you actually want an object rather than a message output | |
[Parameter()] | |
[switch]$OutputAsObject | |
) | |
$indent = 0 | |
$e = $Exception | |
while ($e) { | |
if ($OutputAsObject) { | |
[PSCustomObject]@{ | |
Exception = "{0,$indent}{1}" -f '', $e.GetType().FullName | |
Message = $e.message | |
} | |
} | |
else { | |
Write-output ("{0,$indent}{1} - {2}" -f '', $e.GetType().FullName, $e.message) | |
} | |
$indent += 2 | |
$e = $e.InnerException | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment