与 gaetan224 建议的方式类似,您可以使用 @ControllerAdvice 添加控制器以自定义方式处理异常:
@ControllerAdvice
@RequestMapping(produces = "application/json")
@ResponseBody
public class RestControllerAdvice {
@Autowired
Environment env;
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<?> unhandledPath(final NoHandlerFoundException e) {
//This is for 405 METHOD NOT ALLOWED
//Here you may want to return a ResponseEntity with a custom POJO as body.
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<?> methodNotAllowed(final HttpRequestMethodNotSupportedException e) {
//This is for 404 NOT FOUND
//Here you may want to return a ResponseEntity with a custom POJO as body.
}
}
在 Spring Security 中处理 403 UNAUTHORIZED 时情况会有所不同。您必须编写一个实现 AccessDeniedHandler 接口的@Component。像这样的:
@Component
public class AccessEntryPoint implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest req,
HttpServletResponse res,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
ObjectMapper mapper = new ObjectMapper();
res.setContentType("application/json;charset=UTF-8");
res.setStatus(403);
res.getWriter().write( /*Your custom object may go here*/ );
}
}
但这还不够,您还必须使用以下方法在 WebSecurityConfigureAdapter 实现中设置自定义 AccessDeniedHandler 实现:
@Autowired
AccessEntryPoint accessDeniedHandler;
并将以下内容附加到您的配置方法调用链中:
.exceptionHandling().accessDeniedHandler(accessDeniedHandler).and()
编辑:我忘了添加,为了让 404 自定义处理程序工作,您必须在 application.properties 文件中添加这两行:
spring.resources.add-mappings=false
spring.mvc.throw-exception-if-no-handler-found=true