并行任务失败时如何继续工作流

How to carry-on a workflow when a parallel task fails

我有以下工作流程:

def flow
node('envinf1')
{
    def buildTasks = [:]
    for(i = 0; i < 2; i++) {
        buildTasks[i] = {
            sh 'some command which fails in one of the tasks'
        }
    }
    parallel buildTasks
    echo 'Some message!'
}

当其中一项任务失败时,工作流永远不会到达 echo ... 行,而是整个作业失败并出现异常:

org.jenkinsci.plugins.workflow.cps.steps.ParallelStepException: Parallel step 0 failed at org.jenkinsci.plugins.workflow.cps.steps.ParallelStep$ResultHandler$Callback.checkAllDone(ParallelStep.java:153) ...

是否可以告诉 parallel 步骤继续使用工作流脚本?

buildTasks[i] = {
    try {
        sh 'some command which fails in one of the tasks'
    } catch (e) {
        echo "got ${e} but continuing…"
    }
}

如果您希望构建在最后失败,您可以使用 catchError 步骤

buildTasks[i] = {
    catchError {
        sh 'some command which fails in one of the tasks'
    }
}

或手写等价物

buildTasks[i] = {
    try {
        sh 'some command which fails in one of the tasks'
    } catch (e) {
        echo "failed with ${e}"
        currentBuild.result = 'FAILURE'
    }
}

catchError 确实比手动构建的等价物有一个优势:它通过打印单行消息来处理 AbortException(例如,来自 sh 的非零退出代码),FlowInterruptedException(例如,用户单击停止按钮)通过打印“中止...”消息并设置自定义结果(如 ABORTED),所有其他方式通过打印堆栈跟踪。