[英]Parse exception in try catch block to assign a response code - 2xx, 4xx or 5xx
I have Jenkins plugin written in Java.我有用 Java 编写的 Jenkins 插件。 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.
我正在以三种方式0(2xx 工作流)、1(4xx 工作流)、2(5xx 工作流)捕获 integer 变量中插件执行的所有工作流,并将它们发送到 SignalFX 以获取指标。 Since this is not an API and errors will be mainly caught in try catch workflow.
由于这不是 API,因此错误将主要在 try catch 工作流中捕获。 I wanted to ask how to read error codes from exception class and categorize them in 2xx, 4xx or 5xx.
我想问一下如何从异常 class 中读取错误代码并将它们分类为 2xx、4xx 或 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
我将使用的一些异常类是 -
Exception, IOException, InterruptedException, ParserConfigurationException, SAXException
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.我相信您可能必须添加一种方法来从 e.getMessage() 中识别失败原因,或者有一个自定义异常来帮助您解决问题。
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.此外,如果它是 HTTP 请求相关异常(来自问题详细信息中提到的错误响应代码)或其他内容,您可能需要添加自定义异常,而不是抛出原始异常。 In the custom exception, you can add a custom field to get errorCode from the response code.
在自定义异常中,您可以添加自定义字段以从响应代码中获取 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;
}
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.