Skip to content

CONTRIBUTING: Update information around $PSCmdlet.ThrowTerminatingError #2045

@johlju

Description

@johlju

The documentation should be updated according to this: #1966 (comment)

Also reference: https://stackoverflow.com/questions/49204918/difference-between-throw-and-pscmdlet-throwterminatingerror

When instead using `$PSCmdlet.ThrowTerminatingError()`:
```powershell
$PSCmdlet.ThrowTerminatingError(
[System.Management.Automation.ErrorRecord]::new(
'MyError',
'GS0001',
[System.Management.Automation.ErrorCategory]::InvalidOperation,
'MyObjectOrValue'
)
)
```

I caught this today where I call a public command (or function) from a another public command. Example below.

function Get-Something
{
    [CmdletBinding()]
    param ()

    $PSCmdlet.ThrowTerminatingError(
        [System.Management.Automation.ErrorRecord]::new(
            'Error message',
            'CODE',
            [System.Management.Automation.ErrorCategory]::InvalidOperation,
            'MyObject'
        )
    )

    "Get-Something exiting" # CORRECT: Does not hit this
}

function Start-Something
{
    [CmdletBinding()]
    param ()

    Get-Something -Name $null -ErrorAction 'Stop'

    "Started" # BUG: This line is executed even though Get-Something throw an exception
}

# This hits the bug in Start-Something
Start-Something

# The user must add -ErrorAction 'Stop' to Start-Something to avoid the bug which is not intuitive
Start-Something -ErrorAction 'Stop'

Similar but using Write-Error (non-terminating error):

function Get-Something
{
    [CmdletBinding()]
    param ()

    Write-Error -Message 'Error message' -Category InvalidOperation -TargetObject 'MyObject' -ErrorId 'CODE'

    "Get-Something exiting" # CORRECT: Does not hit this
}

function Start-Something
{
    [CmdletBinding()]
    param ()

    Get-Something -Name $null -ErrorAction 'Stop'

    "Started" # CORRECT: Does not hit this
}

# This works as expected, stops after the exception in Get-Something
Start-Something

Metadata

Metadata

Assignees

Labels

documentationThe issue is related to documentation only.in progressThe issue is being actively worked on by someone.

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions