Manual for library “Base”¶
In this article:
Base.Result¶
The Base.Result class is used to nest every action result of your scripts to get strong and reliable error handling.
Example:
$Assembly = [Reflection.Assembly]::LoadFile("$PSScriptRoot\Base.dll")
$res = New-Object Base.Result("My first script with error handling.")
#------ First part will work ------#
Try
{
$DevisionByTwo = 1 / 2
"Result ByTwo: $DevisionByTwo"
$resTemp = New-Object Base.Result("Result of DevisionByTwo: $DevisionByTwo")
$res.ChildAdd($resTemp)
}
Catch
{
$ErrorMessage = $_.Exception.Message
$ExitCodeClass = New-Object Base.ResultSuperClass+ExitCodeClass([Base.ResultSuperClass+ExitCodeCategory]::Error,[Base.ResultSuperClass+ExitCodeType]::SystemException)
$resError = New-Object Base.Result("Exception thrown: $ErrorMessage",$ExitCodeClass)
$res.ChildAdd($resError)
}
#------ Check if everything went good so far ------#
if ($res.Successful -eq $true)
{
#------ Second part will not work ------#
Try
{
$DevisionByZero = 1 / 0
"Result ByZero: $DevisionByZero"
$resTemp = New-Object Base.Result("Result of DevisionByZero: $DevisionByZero")
$res.ChildAdd($resTemp)
}
Catch
{
$ErrorMessage = $_.Exception.Message
$res.ChildAdd((New-Object Base.Result("Exception thrown: $ErrorMessage", (New-Object Base.ResultSuperClass+ExitCodeClass([Base.ResultSuperClass+ExitCodeCategory]::Error,[Base.ResultSuperClass+ExitCodeType]::SystemException)))))
}
}
$res.Dump()
Expected output:
Result ByTwo: 0.5
+ Ok | My first script with error handling. | 21.04.2017 08:19:28
++ Ok | Result of DevisionByTwo: 0.5 | 21.04.2017 08:19:28
++ SystemException | Exception thrown: Attempted to divide by zero. | 21.04.2017 08:19:28
Powershell functions returning Base.Result¶
To make sure, that self created powershell functions return a Base.Result object, please stick to the following structure:
function MyResultFunction()
{
#EVEY CONSOLE OUTPUT IS PIPED TO $NULL
$Null = @(
$res = New-Object Base.Result("Starting module X...")
#HERE YOUR FUNCTION CONTENT
)
#return , $res: Comma is important character. Do not delete.
return , $res
}
[Base.Result]$res = MyResultFunction
$res.Dump()