如果你看了 docs for docs @ExceptionHandler 您将看到它用于标记处理异常的方法。因此,您必须指定它可以处理的异常(例如, @ExceptionHandler(MyException.class) 要么 @ExceptionHandler({MyException.class, MyOtherException.class}) )。在控制器中发生此类异常时,将调用此方法。
@ExceptionHandler
@ExceptionHandler(MyException.class)
@ExceptionHandler({MyException.class, MyOtherException.class})
@ControllerAdvice 使类中定义的方法可用于所有控制器。
@ControllerAdvice
我不知道你想做什么,但是自从你延伸以来 ResponseEntityExceptionHandler 在里面 @ControllerAdvice 上课,你可以删除 @ExceptionHandler annotation :
ResponseEntityExceptionHandler
@ExceptionHandler annotation
@GetMapping(...) public ResponseEntity<List<User>> testErrors(...) { ... }
如果您想自己处理特定的异常,可以这样做:
@ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(MyException.class) public ResponseEntity<?> handleMyException() { ... } } @Controller public class MyController { @GetMapping(...) public ResponseEntity<List<User>> testErrors(...) { throw new MyException(); } }
现在 handleException() 将在发生错误时调用 testErrors() 。
handleException()
testErrors()
如果只想在一个控制器中处理异常,可以执行以下操作:
@Controller public class MyController { @GetMapping(...) public ResponseEntity<List<User>> testErrors(...) { throw new MyException(); } @ExceptionHandler(MyException.class) public ResponseEntity<?> handleMyException() { ... } }
预计这将无法正常工作。
你试图传入 RestResponseEntityExceptionHandler 作为论点 @ExceptionHandler 测试方法中的注释。这是错误的,因为此批注接受被拦截的异常的类型。
RestResponseEntityExceptionHandler
一般来说,似乎你的位置 @ExceptionHandler 注释似乎是错误的。它放在驻留在实际异常处理类中的方法中。
我建议你对Spring以这种方式处理异常的方式有一个很好的解读。
看看这篇文档: Spring中的异常处理 。