1

I'm trying to write a PowerShell script which sends a Slack notification whenever our build system in unable to push Docker images to Docker Hub. How can I detect and handle the Process exited with code 1 from the docker push command? I've tried the following, but the catch block isn't called.

try {
  docker push $dockerImage;
}catch{
  #Send error details to Slack
}
mklement0
  • 312,089
  • 56
  • 508
  • 622
Yoshi
  • 13
  • 2
  • Does this answer your question? [PowerShell and process exit codes](https://stackoverflow.com/questions/57468522/powershell-and-process-exit-codes) – iRon May 28 '21 at 17:38

1 Answers1

1
  • As of PowerShell 7.2, calls to external programs (such as docker) never cause a statement-terminating error[1] that you can trap with try / catch

    • However, opt-in integration with PowerShell's error handling is being planned for the future - see this RFC and the discussion that preceded it.

    • 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.

mklement0
  • 312,089
  • 56
  • 508
  • 622