问题
I'm setting up a declarative pipeline for Jenkins. In my post
section, I am using slackSend
to notify my team that the build is broken. I'd like to include the failure reason. Is this available in env
or currentBuild
or something else? I haven't seen anything in the documentation, but seems like a common use case
I've seen some posts about using currentBuild.rawBuild.getLog(10)
and that works, but it is just filled with way too much information. I need to zero in on the actual exception
回答1:
Another approach is to use a catchError or at least a try/catch.
Then, as in this answer, you can get the error message: String error = "${e}";
Regarding catchError, you would wrap every step that can potentially fail into a catchError
function. If an error occurs, it will set build.result
to FAILURE, and continue the build.
See catchError, which points out that only the try/catch
approach might be useful to catch the actual error e
(and its string).
You might then add that error string to a global variable, that your post
step could then access.
That would be less verbose and/or more precise than currentBuild.rawBuild.getLog(10)
.
回答2:
If you have a way of invoking the curl command, this is what i used in my bash script recently.
full_error_msg=$(curl -s -k -X GET $url/job/$job_name/lastBuild/consoleText 2> /dev/null | tac | grep Error | head -n 2 | tr -d '\n')
Since the error message usually comes at the end of the build, i use tac command to flip the output, grep for the line containing 'Error', and head the next two lines removing the carriage return between these two Error lines.
来源:https://stackoverflow.com/questions/47843211/get-failure-reason-from-jenkins-pipeline