Java Spring Boot@ControllerAdvice部分工作,不适用于自定义异常
我在Spring Boot 1.5.3中使用@ControllerAdvice注释的ExceptionHandler时遇到了一个特殊情况。它捕获任何异常默认异常,但如果我抛出自定义异常,它不会触发 异常处理程序:Java Spring Boot@ControllerAdvice部分工作,不适用于自定义异常,java,spring,spring-boot,exception-handling,Java,Spring,Spring Boot,Exception Handling,我在Spring Boot 1.5.3中使用@ControllerAdvice注释的ExceptionHandler时遇到了一个特殊情况。它捕获任何异常默认异常,但如果我抛出自定义异常,它不会触发 异常处理程序: @ControllerAdvice public class ResponseEntityExceptionHandler { @ExceptionHandler({ HttpMessageNotReadableException.class }) protected Respons
@ControllerAdvice
public class ResponseEntityExceptionHandler {
@ExceptionHandler({ HttpMessageNotReadableException.class })
protected ResponseEntity<ErrorModel> handleInvalidJson(RuntimeException e, WebRequest request) {
return new ResponseEntity<ErrorModel>(new ErrorModel().message("Could not parse JSON."), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({ NumberFormatException.class })
protected ResponseEntity<ErrorModel> handleInvalidRequest(RuntimeException e, WebRequest request) {
return new ResponseEntity<ErrorModel>(new ErrorModel().message("Invalid request parameter."), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({ CannotCreateTransactionException.class })
protected ResponseEntity<ErrorModel> handleTransactionCreationException(RuntimeException e, WebRequest request) {
return new ResponseEntity<ErrorModel>(new ErrorModel().message("Error connecting to the database, please make sure it is still available."), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({ NotFoundException.class })
protected ResponseEntity<ErrorModel> handleApiException(RuntimeException e, WebRequest request) {
return new ResponseEntity<ErrorModel>(new ErrorModel().message(e.getMessage()), HttpStatus.NOT_FOUND);
}
}
例外情况:
public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
super(code, msg);
this.code = code;
}
}
异常继承自此基类:
public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
super(msg);
this.code = code;
}
}
关于为什么自定义异常会避免ExceptionHandler的检测,您有什么想法吗
如果有必要,我很乐意提供其他信息。对于这种特殊情况,答案是使用
Exception
而不是RuntimeException
,因为NotFoundException只从Exception继承
值得注意的是:
- 要捕获所有异常,可以使用
@ExceptionHandler(Exception.class)
- 如果对异常使用通用名称,请始终检查是否导入了正确的名称
2017-06-05 11:30:20.080 INFO 9076 --- [ main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in responseEntityExceptionHandler
public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
super(code, msg);
this.code = code;
}
}
public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
super(msg);
this.code = code;
}
}