Powershell with Git Command Error Handling - automatically abort on non-zero exit code from external program

前端 未结 2 1837
猫巷女王i
猫巷女王i 2020-12-01 19:17

I use Git to deploy my web application. So in Teamcity I prepare my application (compilation, minify JS and HTML, delete unused files, etc...) and then I have a Powershell b

2条回答
  •  有刺的猬
    2020-12-01 19:49

    I believe the problem here is that the error thrown by git is not trappable by PS.

    Illustration:

    try {
        git push
        Write-Host "I run after the git push command"
    }
    catch {
        Write-Host "Something went wonky"
    }
    

    Note the missing Write-Host from the catch block!

    This is where we need to look at the exit code of the git commands.

    The easiest way (I know) in PowerShell is to check the value of $? (more information on $? here: What is `$?` in Powershell?)

    try {
        git push
        if (-not $?) {
            throw "Error with git push!"
        }
        Write-Host "I run after the git push command"
    }
    catch {
        Write-Host "Something went wonky"
        throw
    }
    

    Check our custom error (now caught by the catch block)!

提交回复
热议问题