我ControllerAdvice用于處理我的應用程式中的例外并且它作業正常。但是,我開始使用 Spring Security,通常我應該在以下方法中捕獲 AuthenticationExceptions。
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException)
throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final Map<String, Object> body = new HashMap<>();
body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
body.put("error", "Unauthorized");
body.put("message", authException.getMessage());
body.put("path", request.getServletPath());
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), body);
}
當我洗掉我的例外處理類時,我可以在這個方法中捕獲 AuthenticationException。但是commence,當我使用我的例外處理機制時,它會在此方法之前捕獲 AuthenticationExceptions 。
我嘗試使用@Order(value = Ordered.LOWEST_PRECEDENCE),但它沒有任何意義。那么,如何commence通過防止 ControllerAdvice 捕獲它們來捕獲此方法中的 AuthenticationException 呢?
uj5u.com熱心網友回復:
所以嘗試添加注釋 @ExceptionHandler(AuthenticationException.class):
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(AuthenticationException.class)
...
public ErrorMessage resourceNotFoundException(AuthenticationException exception) {
...
}
}
在以下位置查看更多資訊:https ://www.baeldung.com/exception-handling-for-rest-with-spring 深入了解 Spring MVC 處理例外:
- https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-exceptionhandlers
- https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-rest-exceptions
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529623.html
上一篇:如何在python中重試
