MikeB
MikeB

Reputation: 2452

Get failure reason from Jenkins pipeline

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

Upvotes: 18

Views: 33520

Answers (2)

ton_K
ton_K

Reputation: 99

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.

Upvotes: 1

VonC
VonC

Reputation: 1329622

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

Upvotes: 3

Related Questions