Groovy Script错误处理

时间:2017-03-31 23:19:29

标签: groovy

我们有以下groovy脚本。我们想为它添加一些错误处理。有时它无法找到URL api / xml。我们如何解决它以处理不出错?

def parameterName = "FRACTURE_NO";
def jenkinsUrl = System.getenv('JENKINS_URL');
def buildNumber = System.getenv('BUILD_NUMBER').toInteger();
def jobUrl = jenkinsUrl + "job/" + System.getenv('JOB_NAME');
def buildNumberUrl = jobUrl + "/" + buildNumber;
def myParameter = System.getenv(parameterName);

def projectXml = new XmlSlurper().parseText(new URL(jobUrl + "/api/xml").getText());
projectXml.build.each {
  def previousBuildNumber = it.number.text().toInteger();
  if(previousBuildNumber < buildNumber)
  {
    def previousBuildNumberUrl = jobUrl + "/" + previousBuildNumber;
    def jobXml = new XmlSlurper().parseText(new URL(previousBuildNumberUrl + "/api/xml").getText());
    if(jobXml.building.text() == "true")
    {
      jobXml.action.parameter.each {
        if(it.name.text() == parameterName) {
          if(it.value.text() == myParameter) {
            def url = new URL(previousBuildNumberUrl + "/stop?token=spark123");
            def connection = url.openConnection();
            connection.setRequestProperty("Authorization", "Basic " + "wscott:26accfcc2cf8a1f3503ac4a70483b4fe".getBytes("UTF-8").encodeBase64());
            connection.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
            connection.setRequestProperty( "Accept", "*/*" );
            connection.addRequestProperty("User-Agent", 
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            connection.setRequestMethod("POST");
            connection.connect();
            connection.content.text;
            println "Stopping " + previousBuildNumber;
          }
        }
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用try / catch构造。该错误很可能是“FileNotFoundException”,当http响应为404(未找到)时抛出该错误。其他错误很可能,所以我不会太具体而且会捕获“IOException”,我认为它涵盖了该调用的所有HTTP错误:

try {
    String xmlContent = new URL(previousBuildNumberUrl + "/api/xml").getText()
} catch(IOException e) {
    // handle error...
}

我认为你有一个downvote,因为这个问题有很多错误,可以抽象掉。请查看How to create a Minimal, Complete, and Verifiable example

编辑:回答下面的问题,“IOException”应该足够了,但你可以使用“Exception”来代替所有内容......虽然这被认为是不好的做法,因为你最终还会捕捉到“编程错误”这个定义无法以编程方式处理。但我怀疑这不是一个主要的问题。