As of PowerShell 7.3, calls to external programs (such as docker) never cause a statement-terminating error[1] that you can trap with try / catch; similarly, stderr output from external program is (rightfully) not considered error output by PowerShell, and therefore $ErrorActionPreference = 'Stop' has no effect on it (for legacy exceptions in Windows PowerShell, see this answer).
However, opt-in integration with PowerShell's error handling may be implemented in the future; as of v7.3, there is an experimental feature named PSNativeCommandErrorActionPreference (which may become an official feature):
- If this feature is enabled (
Enable-ExperimentalFeature PSNativeCommandErrorActionPreference) and the associated $PSNativeCommandErrorActionPreference preference variable is set to $true, any external-program call that reports a nonzero exit code automatically triggers a PowerShell error in response (obviating the need for explicit $LASTEXITCODE -ne 0 checks), which then integrates with PowerShell's own error handling.[2]
In general, note that a statement-terminating PowerShell error (which can be caught with try / catch) does occur if PowerShell fails to even launch a command, such as when you supply a non-existent executable name or path; e.g.:
try { nosuchexe foo bar }
catch { Write-Warning "Failed to invoke nosuchexe: $_" }
The automatic $LASTEXITCODE variable reflects the process exit code of the most recently executed external program. By convention, exit code 0 signals success, anything else an error condition.
Therefore:
docker push $dockerImage
if ($LASTEXITCODE -ne 0) {
#Send error details to Slack
}
See also:
- This answer has more information on exit-code processing in PowerShell.
[1] The only exception is a bug, present up to PowerShell 7.1, where the combination of redirecting stderr output (2> or *>) with $ErrorActionPreference = 'Stop' unexpectedly causes a script-terminating error if there's actual stderr output - see this answer.
[2] Unfortunately, as of v7.3.0, the automatically triggered PowerShell error is a non-terminating error rather than a statement-terminating one; the latter would make more sense, as it would allow it to be selectively caught with a try statement - see GitHub issue #18368.