Private/ThrowError.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using namespace System.Management.Automation

function ThrowError {
    [CmdletBinding()]
    param(
        [Parameter(Position=0, Mandatory, ParameterSetName='New')]
        [ValidateNotNullOrEmpty()]
        [Exception]
        $Exception,

        [Parameter(Position=1, Mandatory, ParameterSetName='New')]
        [ValidateNotNullOrEmpty()]
        [string]
        $Id,

        [Parameter(Position=2, Mandatory, ParameterSetName='New')]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.ErrorCategory]
        $Category,

        [Parameter(Position=3, ParameterSetName='New')]
        [AllowNull()]
        [object]
        $Target,

        [Parameter(Position=0, Mandatory, ParameterSetName='Rethrow')]
        [ValidateNotNullOrEmpty()]
        [System.Management.Automation.ErrorRecord]
        $ErrorRecord,

        [Alias('PSCmdlet')]
        [System.Management.Automation.PSCmdlet]
        $ErrorContext,

        [switch]
        $Show
    )
    end {
        if (-not $ErrorContext) {
            foreach ($frame in (Get-PSCallStack)) {
                if ($frame.Command -eq $MyInvocation.MyCommand.Name) { continue }
                if ($ErrorContext = $frame.GetFrameVariables().PSCmdlet.Value) { break }
            }
            if (-not $ErrorContext) { $ErrorContext = $PSCmdlet }
        }
        if ($PSCmdlet.ParameterSetName -eq 'New') {
            $ErrorRecord = [ErrorRecord]::new($Exception, $Id, $Category, $TargetObject)
        }
        if ($psEditor -and $Show.IsPresent) {
            $psEditor.Window.ShowErrorMessage($ErrorRecord.Exception.Message)
        }
        $ErrorContext.ThrowTerminatingError($ErrorRecord)
    }
}