即使在应用程序捕获特定异常后仍执行Spring ExceptionHandler

时间:2018-11-06 19:52:15

标签: java spring error-handling controller

我在春季处理异常时遇到麻烦。

我有这个@Controller,它调用一个@Service,还有一个单独的ControllerAdvice。

该服务有两种方法,方法A和方法B。 MethodB是发生异常的地方。在以特定形式捕获后,例如DuplicateKeyException父类再次捕获它。如果我让父母不像抓Exception那样宽泛,例如仅捕获InterruptedExceptionExecutionException,控制器建议接收错误并返回错误响应。

是否有一种规范的方法来捕获此特定异常DuplicateKeyException并继续进行处理,就好像什么都没有发生并在不触发ControllerAdvice的情况下将响应返回给客户端一样?

  

控制器建议

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
       //Do some error processing and return a view for the client 
        return mav;
    }

}
  

控制器

@Controller
public ControllerClass(){  
    @RequestMapping("/test", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseEntity<Omitted> getCustomerData(omitted) throws SQLException, JsonProcessingException {
        CustomerData customerData = serviceCalss.methodA();
        //futher processing and return valid return type
        return new ResponseEntity<Omitted>();
    }
}
  

服务

public class ServiceClass{
    public CustomerData methodA(){
        try {
                @SuppressWarnings("unchecked")
                Collection<SomeType> someCollection = (Collection<SomeType>) result.get(); // this line possibly throws InterruptedException, ExecutionException
                //do some stuff then call methodB
                methodB();
            }catch (Exception e) {
                logger.error("Error getting aggregated results", e);
                //Custom Error processing 
            }
        }      
}


 public void methodB() {
        try {
                persistence.insertNewData(data);
            }catch(DuplicateKeyException dke) {
                logger.warn("Unable to create blah, Specific Error Message{}", dke);
            }catch (SQLException e) {
                Error error = new Error();
                error.developerinfo = e.toString();
                error.text = e.getMessage();
                throw new CustomEXceptionWhichExtendsException("custom error message not related to this example, error);
            }
        }
}

0 个答案:

没有答案