我在 Spring 天遇到异常处理问题 .

我有@Controller调用@Service,我有一个单独的ControllerAdvice .

该服务有两种方法,methodA和methodB . MethodB是发生异常的地方 . 以特定形式捕获后,例如 DuplicateKeyException 父类再次捕获它 . 如果我使父母不那么笼统而不仅仅是 grab Exception ,例如只 grab 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);
            }
        }
}