如果我在 catch 块中使用 "instanceof" 运算符,声纳显示问题
Sonar Showing issue if I used "instanceof" operator in catch block
如何重构我正在使用的 catch 块下面 java11
代码
public String methodName(ClassRequest request, Destination ABC) {
try {
<Some Code Here>
} catch (Exception e) {
log.error("error", ABC, e);
if(e instanceof ABCRestException ||
(ABC == PREM && (e instanceof HttpServerErrorException || e instanceof HttpClientErrorException))) {
throw e;
} else if(e instanceof HttpServerErrorException) {
throw new ABCRestException(request.getAId(), "unexpected_error", "Some Message", e, INTERNAL_SERVER_ERROR);
} else if(e instanceof HttpClientErrorException) {
throw new ABCRestException(request.getAId(), "missing_field", "Some Message", e, BAD_REQUEST);
} else {
throw new ABCRestException(request.getAId(), "unexpected_error", "Some Massage", e, INTERNAL_SERVER_ERROR);
}
}
}
我如何重构这段代码 Means catch 块
你只需要像这样的两个 catch 块
public String methodName(ClassRequest request, Destination ABC) {
try {
<Some Code Here>
} catch (HttpServerErrorException e) {
log.error("error", ABC, e);
if (ABC == PREM){
throw e;
}else{
throw new ABCRestException(request.getAId(), "unexpected_error", "Some Message", e, INTERNAL_SERVER_ERROR);
}
} catch (HttpClientErrorException e){
if (ABC == PREM){
throw e;
}else{
throw new ABCRestException(request.getAId(), "missing_field", "Some Message", e, BAD_REQUEST);
}
}
}
如果你想重用一些逻辑,你可以写一个私有方法并在catch块中调用它
如果两个或多个异常共享完全相同的逻辑,您还可以使用 multi-catch,它会在同一块中捕获各种异常
try{
codeGoesVroomVroomAndThrows()
}catch(ExceptionA | ExceptionB e){
//do something
}
如何重构我正在使用的 catch 块下面 java11 代码
public String methodName(ClassRequest request, Destination ABC) {
try {
<Some Code Here>
} catch (Exception e) {
log.error("error", ABC, e);
if(e instanceof ABCRestException ||
(ABC == PREM && (e instanceof HttpServerErrorException || e instanceof HttpClientErrorException))) {
throw e;
} else if(e instanceof HttpServerErrorException) {
throw new ABCRestException(request.getAId(), "unexpected_error", "Some Message", e, INTERNAL_SERVER_ERROR);
} else if(e instanceof HttpClientErrorException) {
throw new ABCRestException(request.getAId(), "missing_field", "Some Message", e, BAD_REQUEST);
} else {
throw new ABCRestException(request.getAId(), "unexpected_error", "Some Massage", e, INTERNAL_SERVER_ERROR);
}
}
}
我如何重构这段代码 Means catch 块
你只需要像这样的两个 catch 块
public String methodName(ClassRequest request, Destination ABC) {
try {
<Some Code Here>
} catch (HttpServerErrorException e) {
log.error("error", ABC, e);
if (ABC == PREM){
throw e;
}else{
throw new ABCRestException(request.getAId(), "unexpected_error", "Some Message", e, INTERNAL_SERVER_ERROR);
}
} catch (HttpClientErrorException e){
if (ABC == PREM){
throw e;
}else{
throw new ABCRestException(request.getAId(), "missing_field", "Some Message", e, BAD_REQUEST);
}
}
}
如果你想重用一些逻辑,你可以写一个私有方法并在catch块中调用它
如果两个或多个异常共享完全相同的逻辑,您还可以使用 multi-catch,它会在同一块中捕获各种异常
try{
codeGoesVroomVroomAndThrows()
}catch(ExceptionA | ExceptionB e){
//do something
}