如何处理 Jenkins 中的 UnknownHostException 错误

问题描述 投票:0回答:1

我的 Jenkinsfile 看起来像这样:

import jenkins.org.apache.commons.validator.routines.DomainValidator

pipeline {
    agent any

    stages {
        stage ('Validate actions') {
            steps {
                script {
                    env.TEST_FQDN = "fully.unexistent.tld"
                    if (DomainValidator.getInstance().isValid(env.TEST_FQDN)) {
                        echo "the fqdn is valid"
                    } else {
                        currentBuild.result = 'ABORTED'
                        error('the fqdn is invalid')
                    }
                }
            }
        }
    }
}

如果

env.TEST_FQDN
具有有效(可解析)域,则测试将正常运行。但我也想用一个不存在的域来测试它。如果这样做,那么我会在构建结束时收到异常错误:

...
[Pipeline] End of Pipeline
Also:   hudson.remoting.ProxyException: org.jenkinsci.plugins.workflow.actions.ErrorAction$ErrorId: 195aa648-a608-48dd-96bb-2f0fbb779d56
hudson.remoting.ProxyException: java.net.UnknownHostException: fully.unexistent.tld: Name or service not known
...

什么是正确的,因为该主机名不存在。我想做的是以某种方式处理

UnknownHostException
,然后如果触发此异常,我将中止 Jenkins 构建,而不是在最后崩溃构建。我该如何处理管道中的异常?

我也尝试过另一个课程:

if (InetAddress.getByName(env.TEST_FQDN).isReachable(3000)) {
    echo "the fqdn is valid"
} else {
    currentBuild.result = 'ABORTED'
    error('the fqdn is invalid')
}

但看起来它的工作原理是一样的。如果主机不存在,则会抛出

UnknownHostException

也许 java/groovy 中有另一个类/方法来检查 fqdn 是否存在?

更新:

我尝试更改代码以在内部使用 try-catch,但错误是相同的,不知何故管道无法捕获任何异常:

import jenkins.org.apache.commons.validator.routines.DomainValidator

pipeline {
    agent any

    stages {
        stage ('Validate actions') {
            steps {
                script {
                    env.TEST_FQDN = "fully.unexistent.tld"
                    try {
                    DomainValidator.getInstance().isValid(env.TEST_FQDN)
                } catch (err) {
                        echo err.getMessage()
                        currentBuild.result = 'ABORTED'
                    }
                }
            }
        }
    }
}
jenkins groovy jenkins-groovy
1个回答
0
投票

isValid()
不会引发任何异常,也不会尝试解析名称。请参阅实现。它根据正则表达式检查名称,仅此而已。所以你不需要捕获任何异常,你原来使用
if
的方法是完全有效的。寻找启动某些网络通信或至少名称解析的不同命令。

© www.soinside.com 2019 - 2024. All rights reserved.