簡體   English   中英

解析 try catch 塊中的異常以分配響應代碼 - 2xx、4xx 或 5xx

[英]Parse exception in try catch block to assign a response code - 2xx, 4xx or 5xx

我有用 Java 編寫的 Jenkins 插件。 我正在以三種方式0(2xx 工作流)、1(4xx 工作流)、2(5xx 工作流)捕獲 integer 變量中插件執行的所有工作流,並將它們發送到 SignalFX 以獲取指標。 由於這不是 API,因此錯誤將主要在 try catch 工作流中捕獲。 我想問一下如何從異常 class 中讀取錯誤代碼並將它們分類為 2xx、4xx 或 5xx。 有一些我可以遵循的規則嗎?

    try {
            Thread.sleep(60 * 1000);
        } catch (InterruptedException e) {
            sendToSignalFX(0,data);    // 0 means successful state
        }

我將使用的一些異常類是 - Exception, IOException, InterruptedException, ParserConfigurationException, SAXException

我相信您可能必須添加一種方法來從 e.getMessage() 中識別失敗原因,或者有一個自定義異常來幫助您解決問題。
此外,如果它是 HTTP 請求相關異常(來自問題詳細信息中提到的錯誤響應代碼)或其他內容,您可能需要添加自定義異常,而不是拋出原始異常。 在自定義異常中,您可以添加自定義字段以從響應代碼中獲取 errorCode。

// MyCustomException.java
public class MyCustomException extends Exception {

  String errorReason;
  int errorCode;
  
  public MyCustomException(Throwable throwable, String errorReason, int errorCode) {
    super(errorReason, throwable);
    this.errorReason = errorReason;
    this.errorCode = errorCode;
  }
}

在您的請求處理程序代碼中:

try {
  // otherCode which might cause IOException
  // ...
  Response response = myHttpRequest();
  if (!response.isSuccessful()) {
    // identify the error code and set corresponding errorCode to MyCustomException. errorCode
    int errorCode = 0;
// parse response.getStatusCode() or equivalent of the library and reassign the value of errorCode
    throw new MyCustomException(e, e.getMessage(), errorCode);
  }
  // ...
  // otherCode which might cause IOException
} catch (Exception | IOException e) {
  throw new MyCustomException(e, e.getMessage(), 0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM