Skip to content

Instantly share code, notes, and snippets.

@Xainey
Created February 15, 2017 17:39
Show Gist options
  • Save Xainey/f1b58368b25645b347f92ebc7416a472 to your computer and use it in GitHub Desktop.
Save Xainey/f1b58368b25645b347f92ebc7416a472 to your computer and use it in GitHub Desktop.
Testing throwing custom exceptions
# Generate a custom error without C#
function New-ErrorRecord ([string] $ErrorID, [string] $Message, [HashTable] $Custom)
{
$errorCategory = [Management.Automation.ErrorCategory]::InvalidResult
$exception = New-Object Exception $Message
$errorRecord = New-Object Management.Automation.ErrorRecord $exception, $ErrorID, $errorCategory, $Custom
return $errorRecord
}
# Helper functions throw errors
function Do-Something
{
throw (New-ErrorRecord -ErrorID "MyModule.Friday" -Message "You probably shouldn't do this today.")
}
function Do-SomethingElse
{
throw (New-ErrorRecord -ErrorID "MyModule.Whoops" -Message "Well that sucked." -Custom @{Prefix = "Whoops"})
}
function Do-SomethingAweful
{
throw [System.Exception] "This should cause terminating error"
}
function Do-SomethingAweful2
{
throw "This should cause terminating error"
}
function Do-SomethingDifferent
{
throw [System.FormatException] "That format sucks :("
}
# Main function calls helpers and handles exceptions
function Main($helper)
{
try
{
. $helper
}
# More specific Exceptions must be caught first
catch [System.FormatException]
{
Write-Host $_.Exception.Message -ForegroundColor Yellow
}
catch [System.Exception]
{
# List of my Custom Errors, If logic below to handle
$CustomErrors = @("MyModule.Friday","MyModule.Whoops")
# Rethrow if not one of my custom errors
if($_.FullyQualifiedErrorId -notin $CustomErrors)
{
throw $_.Exception
}
# Custom Output
$message = $_.Exception.Message
if($_.TargetObject.Prefix)
{
$message = "{0}: {1}" -f $_.TargetObject.Prefix, $_.Exception.Message
}
Write-Host $message -ForegroundColor Cyan
}
}
# Call contrived main function
cls
Main Do-Something
Main Do-SomethingElse
Main Do-SomethingDifferent
Main Do-SomethingAweful
Main Do-SomethingAweful2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment