Search code examples
javaexceptionresponsehttp-response-codes

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


I have Jenkins plugin written in Java. I am capturing all the workflows of execution of plugin in a integer variable in three ways 0(2xx workflows), 1(4xx workflows), 2(5xx workflows) and sending them to SignalFX for metrics. Since this is not an API and errors will be mainly caught in try catch workflow. I wanted to ask how to read error codes from exception class and categorize them in 2xx, 4xx or 5xx. Are there some rules which I can follow by?

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

Some of the exceptions classes I will be using are - Exception, IOException, InterruptedException, ParserConfigurationException, SAXException


Solution

  • I believe you may have to add a method to identify the failure reason from e.getMessage() for one OR have a custom exception to help with your case.
    Also if it’s an HTTP request-related exception (from the error response code mentioned in the question details) or something, you may want to add a custom exception, instead of throwing the original exception. In the custom exception, you can add a custom field to get errorCode from the response code.

    // 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;
      }
    }
    

    And in your request handler code:

    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);
    }