jenkins pipline异常捕获

  1. timeout机制以及异常捕获
https://e.printstacktrace.blog/how-to-time-out-jenkins-pipeline-stage-and-keep-the-pipeline-running/

pipeline {
    agent any
    options{
        timestamps()
    }
    stages {
        stage("A") {
            options {
                timeout(time: env.timeout, unit: "SECONDS")
                //MINUTES
            }

            steps {
                script {
                    Exception caughtException = null

                    catchError(buildResult: 'SUCCESS', stageResult: 'ABORTED') { 
                        try { 
                            echo "Started stage A"
                            sleep(time: 5, unit: "SECONDS")
                        } catch (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException e) {
                            error "Caught ${e.toString()}" 
                        } catch (Throwable e) {
                            caughtException = e
                        }
                    }

                    if (caughtException) {
                        error caughtException.message
                    }
                }
            }
        }

        stage("B") {
            steps {
                echo "Started stage B"
            }
        }
    }
}


  1. catchError 总体是failed,对应的stage也是failed,但是后面的stage还能正常执行
pipeline {
    agent any
    stages {
        
        stage('1') {
            steps {
                // build job:'test'
                echo 'in 1'
            }
        }
        
        stage('2') {
            steps {
                catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                    build job:'test'
                }
            }
        }
        
        stage('3') {
            steps {
               echo 'in 3'
            }
        }
        
        
    }
}



  1. try 总体的build是pass的,每个stage也是pass
pipeline {
    agent any
    stages {
        
        stage('1') {
            steps {
                 script {
                     try{
                          build job: 'test'
                      }    
                      catch (err){
                          echo "test failed"
                      }
                 }
            }
        }
        
        stage('2') {
            steps {
                 script {
                     try{
                          build job: 'test'
                      }    
                      catch (err){
                          echo "test failed"
                      }
                 }
            }
        }
        
        
        stage('3') {
            steps {
                 script {
                     try{
                          build job: 'test'
                      }    
                      catch (err){
                          echo "test failed"
                      }
                 }
            }
        }
        
        
    }
}
posted @ 2021-05-06 17:10  该显示昵称已被使用了  阅读(1244)  评论(0编辑  收藏  举报