6

我有一个包含多个步骤的管道,例如:

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

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

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

如果工作中出现问题,我想发送电子邮件,无论错误在哪里触发,我如何发送电子邮件,例如:

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

3 回答 3

8

我认为这是使用 jenkins build in post 部分而不是使用 try catch 的更好方法:

pipeline {
  agent any
    stages {
      stage('whatever') {
        steps {
          ...
        }
      }
    }
    post {
        always {
          step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "example@example.com",
            sendToIndividuals: true])
        }
      }
    }
  }
}
于 2017-05-19T09:01:26.367 回答
5

我做了什么来在我的邮件中包含有关失败的有用信息:

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: '',
         cc: '',
         charset: 'UTF-8',
         from: '',
         mimeType: 'text/html',
         replyTo: '',
         subject: "ERROR CI: Project name -> ${env.JOB_NAME}",
         to: "${mails_to_notify}",
         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}";
    error "${error}"
}
于 2016-08-11T20:03:08.060 回答
3

好吧,你的想法是绝对正确的,你只需要mail在块之后移动catch或使用finally. 示例(伪代码):

try {
    //code
    email = 'success'
} catch(Exception e) { 
    // error handler: logging
    email = 'failure'
}
send email

catchError或者使用内置管道的相同方法:

result = 'failure'
catchError { // this catches all exceptions and set the build result
    //code
    result = 'success' // we will reach this point only if no exception was thrown
}
send result 

或使用finally

try {
    //code
} finally { 
    send email
}
于 2016-04-29T23:20:07.313 回答