我有一个带有 REST 方法的 Controller 类,可以抛出各种异常。我已决定使用 @ControllerAdvice 和 @ExceptionHandler 作为我的处理程序方法在单独的类中处理这些异常。 但是,我有一个问题,我的 REST 方法使用来自另一个库的注释。该库捕获了我的 REST 方法也抛出的异常。 现在我正在全局处理异常,而不是直接通过 REST 方法中的 try/catch,我的异常总是被其他库捕获,而不是被我自己的处理程序方法捕获。显然,由于注释,我正在使用的库中的其他方法获胜。 如何将异常处理绑定(bind)到我自己的类以防止它被其他任何人捕获?
我的 REST 方法:
@SomeLibraryAnnotation
@PostMapping(path = "/add", consumes = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity< ? > addItem(@RequestHeader HttpHeaders headers, @RequestBody MyDTO myDTO)
throws UnsupportedOperationException {
doSomethingWith(myDTO);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
我的异常处理类:
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(UnsupportedOperationException.class)
public ResponseEntity<?> handleUnsupportedOperationException(UnsupportedOperationException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(e.getMessage());
}
}
由于库方法也捕获了 UnsupportedOperationException,它因 @SomeLibraryAnnotation 而获胜,并且我的处理程序类中从未处理过该异常。
最佳答案
您可以尝试在 MyExceptionHandler
类中使用 @Order
或 @Priority
,如 Setting Precedence of Multiple @ControllerAdvice @ExceptionHandlers 中所述。 .
这将使 Spring 有机会使用您的类而不是 @SomeLibraryAnnotation
指定的类。然而,不知道 Spring 如何在上下文初始化时解释其他注释,这只是一个猜测。
关于java - 仅将异常处理绑定(bind)到 @ControllerAdvice 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54655415/