Throw exception in powershell with original nesting error
I am a C # developer trying to build something useful using PowerShell. This is why I keep trying to use famous idioms from the .NET world in PowerShell.
I am writing a script that has different levels of abstraction: database operations, file manipulation, etc. At some point, I would like to catch the error and turn it into something more meaningful to the end user. This is a common pattern for C # / Java / C ++ code:
Function LowLevelFunction($arg)
{
# Doing something very useful here!
# but this operation could throw
if (!$arg) {throw "Ooops! Can't do this!"}
}
Now I would like to call this function and wrap the error:
Function HighLevelFunction
{
Try
{
LowLevelFunction
}
Catch
{
throw "HighLevelFunction failed with an error!`nPlease check inner exception for more details!`n$_"
}
}
This approach is almost what I need because it HighLevelFunction
will throw a new error and the root cause of the original error will be lost!
In C # code, I can always create a new exception and provide the original exception as an inner exception. In this case, it HighLevelFunction
will be able to communicate its errors in a form that is more meaningful to its customers, but still provide internal details for diagnostic purposes.
The only way to print the original exception in PowerShell is to use a variable $Error
that holds all exceptions. This is fine, but the user of my script (himself at the moment) has to do more things that I would like.
So the question is: Is there a way to raise the exception in PowerShell and present the original error as an internal error?
source to share
You can add a new exception to your block catch
and specify a base exception:
# Function that will throw a System.IO.FileNotFoundExceptiopn
function Fail-Read {
[System.IO.File]::ReadAllLines( 'C:\nonexistant' )
}
# Try to run the function
try {
Fail-Read
} catch {
# Throw a new exception, specifying the inner exception
throw ( New-Object System.Exception( "New Exception", $_.Exception ) )
}
# Check the exception here, using getBaseException()
$error[0].Exception.getBaseException().GetType().ToString()
source to share