我有用Java编写的Jenkins插件。我用0(2xx工作流)、1(4xx工作流)、2(5xx工作流)三种方式捕获了一个整数变量中插件执行的所有工作流,并将它们发送给SignalFX进行度量。因为这不是一个API,错误将主要捕获在try工作流中。我想问如何从异常类读取错误代码,并在2xx、4xx或5xx中对它们进行分类。有什么我可以遵守的规则吗?
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
sendToSignalFX(0,data); // 0 means successful state
}我将使用的一些例外类是- Exception, IOException, InterruptedException, ParserConfigurationException, SAXException。
发布于 2022-08-16 05:52:59
我相信您可能需要添加一个方法来从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);
}https://stackoverflow.com/questions/73364602
复制相似问题