Daniel Hernández Daniel Hernández - 3 months ago 77
Groovy Question

jenkins notifying error by sending mail in Pipeline (former known as Workflow)

I have a pipeline with multiple steps, for example:

stage 'dev - compile'
node('master') {
//do something
}

stage 'test- compile'
node('master') {
//do something
}

stage 'prod- compile'
node('master') {
//do something
}


I want to send a email if something goes wrong in the job, how can I send an email no matter where the error got triggered, something like:

try {
/**
all the code above
**/
} catch(Exception e) {
mail the error
}

Answer

What I did to include useful information in my mail about the failure:

try {
    stage 'checkout cvs'
    node('master') {
        /** CODE **/
    }

    stage 'compile'
    node('master') {
        /** CODE **/
    }

    stage 'test unit'
    node('master') {
        /** CODE **/
    }   

    stage 'package'
    node('master') {
        /** CODE **/
    }

    stage 'nexus publish'
    node('master') {
        /** CODE **/
    }

    stage 'Deploy to App Server'
    node('master') {
        /** CODE **/            
    }

} catch(e) {
    String error = "${e}";
    // Make the string with job info, example:
    // ${env.JOB_NAME}
    // ${env.BUILD_NUMBER} 
    // ${env.BUILD_URL}
    // and other variables in the code
    mail bcc: '', body: "<b>${pivote}</b><br>\n\nMensaje de error: ${error}\n\n<br>Projecto: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br> URL de build: ${env.BUILD_URL}", cc: '', charset: 'UTF-8', from: '', mimeType: 'text/html', replyTo: '', subject: "ERROR CI: Project name -> ${env.JOB_NAME}", to: "${mails_to_notify}";
    error "${error}"
}