【发布时间】:2021-12-12 03:35:40
【问题描述】:
在 SonarQube 扫描中,它捕获了一些错误,它说方法捕获了一个异常,并抛出了一个不同的异常,而不包含原始异常。
看下面的代码,
try {
// something
// can include nested exceptions...
} catch (CustomException ex) {
throw ex;
} catch (Exception ex) {
// Issue is here
throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "exception message: "+ ex);
}
下面是自定义异常 DTO
class CustomException {
HttpStatus status;
String message;
// Getter & Setter....
}
我可以通过这样做解决这个问题,
catch (Exception ex) {
CustomException exception = new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "message" + ex);
exception.initCause(ex);
throw exception;
}
上述解决方案很好,但对于目前的情况并不理想,因为那时我必须进行大量更改。
我的问题是,为什么下面的代码不起作用。是因为我将 ORIGINAL CAUSE 作为字符串传递吗?
throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "exception message: "+ ex);
如果“ex”作为字符串传递是问题,那么有没有办法解决它,因为我的 CustomException 只能接受“字符串”字段并且我不能更改任何字段的类型?有什么建议吗?
【问题讨论】:
标签: java spring-boot sonarqube