简体   繁体   中英

Handling Jenkins Groovy script exceptions

I am executing a C# exe, CRS.exe, that I expect to return a non-zero value, such as -1. I am using ps to get the value back, and have this within a stage:

  try{            
      pcode = (powershell(returnStdout: true, script: 'return Invoke-Expression -Command \" .\\perfmon\\CRS.exe hello \"'))''
      echo "Pcode =  ${pcode} "
      }
  catch (err) {echo err.message }
  echo "Pcode =  ${pcode} "

Based on this post, "Normally, a script which exits with a nonzero status code will cause the step to fail with an exception." -- Jenkins pipeline bubble up the shell exit code to fail the stage I want to handle this non-zero result, is the exception handler the only way? Results of above run:

    Running PowerShell script
tester arg = hello    
[Pipeline] echo
script returned exit code -1
[Pipeline] echo
Pcode =  null 

Interestingly enough, a char return seems to be fine? This returns without throwing an exception

 icode = (powershell(returnStdout: true, script: 'return Invoke-Expression -Command \'.\\perfmon\\zipInstaller.ps1 -urlString ' + fileContents + "'"))
                echo "icode =  ${icode} "

Results in 
[Pipeline] {
[Pipeline] powershell
[Chris] Running PowerShell script
[Pipeline] echo
icode =  -5

I would like to catch the return codes from the exe's and manage my groovy pipelines flow based on that. Any insight would be greatly appreciated.

Instead of using returnStdout: true , try using returnStatus: true . It should always return the exit code. Not as helpful if you need the output from the powershell command all at once (without returnStdout , it will just print output to the Jenkins log), but as a workaround for that you could pipe output to a file and then print that out.

Another option (but it's ugly, so I don't recommend it) is to call Powershell from a bat command. bat should mask the error code for the powershell command, so Jenkins won't get excited and fail automatically, and you'll still get stdout. Obviously not too helpful if you actually wanted the error code though. Your line would look something like

pcode = (bat(returnStdout: true, script: 'Powershell.exe "return Invoke-Expression -Command \" .\\perfmon\\CRS.exe hello \"'"))

That line will need a bit of refining, but it might be another option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM