Jenkins Groovy流水线调用Octane API无法获取业务错误信息
在Jenkins流水线Groovy脚本中捕获Octane API的业务错误详情
调用Octane API查询测试套件关联信息时,浏览器能返回明确的业务错误JSON:
{"error_code":"platform.unknown_field","correlation_id":"xxxxxx","description":"The entity type 'test_suite_link_to_manual' does not have a field/s by name/s 'manual_test'","description_translated":"The entity type 'test_suite_link_to_manual' does not have a field/s by name/s 'manual_test'","properties":{"entity_type":"test_suite_link_to_manual","field_name":"manual_test"},"business_error":true}
但Jenkins流水线的Groovy脚本仅抛出java.io.IOException: Server returned HTTP response code: 400 for URL:,且捕获到的errorStream内容是nginx的400 HTML页面,无法获取上述业务错误详情。
问题根源
- 代码执行顺序错误:脚本中先调用
connection.inputStream.text,当API返回非200状态码时,这一步会直接抛出IOException,导致后续读取responseCode和处理errorStream的逻辑无法执行。 - 请求头缺失:未指定
Accept: application/json请求头,Octane API可能未返回JSON格式的错误,转而由nginx返回HTML错误页。
解决方案
调整代码逻辑,先获取响应状态码,再根据状态码选择读取输入流或错误流;同时添加请求头确保API返回JSON格式错误信息,优化流的处理方式避免资源泄漏。
修改后的Groovy代码
def connection = new URL(url).openConnection() try { attempt++ if (!isCookieValid(3)) { cookie = getCookie(3) } connection.setRequestMethod("GET") connection.setRequestProperty("Cookie", cookie) // 添加Accept请求头,指定接收JSON格式响应 connection.setRequestProperty("Accept", "application/json") // 先获取响应状态码,避免提前读inputStream抛出异常 def responseCode = connection.responseCode if (responseCode == 200) { // 读取正常响应流 def responseText = "" try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.inputStream))) { responseText = reader.text } echo "Test suite link to manual tests retrieved successfully" return responseText } else { // 读取错误流中的业务错误信息 def errorMessage = "" if (connection.errorStream != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.errorStream))) { errorMessage = reader.text } echo "业务错误详情:\n${errorMessage}" } // 可根据error_code字段做额外逻辑处理 } } catch (Exception e) { def errorMessage = "" if (connection.errorStream != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.errorStream))) { errorMessage = reader.text } echo "捕获到异常,业务错误详情:\n${errorMessage}" } if (attempt == retries) { echo "Failed to get test suites link to manual tests after ${retries} attempts" return null } echo "Attempt ${attempt} failed: ${e.message}. Retrying..." sleep(5) }
关键改动说明
- 调整执行顺序:先获取
responseCode,再决定读取哪个流,避免提前读取inputStream触发异常。 - 添加Accept请求头:让Octane API明确返回JSON格式的错误响应,而非nginx的HTML错误页。
- 使用try-with-resources:自动关闭BufferedReader,避免资源泄漏,简化代码结构。
- 统一错误输出:无论是正常非200状态还是捕获到异常,都能读取并输出errorStream中的业务错误详情。
修改后,Jenkins控制台就能输出和浏览器一致的Octane业务错误JSON,方便快速定位问题。
内容的提问来源于stack exchange,提问作者mo-ta-to
相关产品推荐
相关产品推荐

