【问题标题】:Sonar Showing issue if I used "instanceof" operator in catch block如果我在 catch 块中使用“instanceof”运算符,声纳显示问题
【发布时间】:2021-09-23 07:16:17
【问题描述】:

如何在我使用 java11 的 catch 块下重构 代码

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

我如何重构这段代码意味着 catch 块

【问题讨论】:

  • 添加单独的 catch 块
  • 我可以定义一个catch块吗?并在 catch 块中声明所有异常
  • @PallaviSingh 这不是正确的方法,catch 是专门针对异常的,所以你不需要使用 inistance of
  • @PallaviSingh 你可以做的是调用 catch 块内的方法传递异常并在那里运行一些通用逻辑
  • @PallaviSingh 是的,这就是它抱怨的原因

标签: java try-catch


【解决方案1】:

你只需要两个像这样的 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
}

【讨论】:

    猜你喜欢
    • 2010-12-31
    • 2015-03-17
    • 2012-12-15
    • 1970-01-01
    • 2021-12-29
    • 2019-02-06
    • 2017-05-04
    • 2012-07-29
    • 2021-11-09
    相关资源
    最近更新 更多