首先,为要处理的每个特殊HTTP错误定义一个异常。在这里,我只是定义一个处理
404 Not Found案例:
public class NotFoundException extends RuntimeException {}要完全替换默认的Spring
Boot的错误处理机制,我们可以实现
ErrorController。
ErrorController我将在这里扩展而不是仅仅实现
AbstractErrorController,它实现
ErrorController并提供一些辅助方法,例如
getStatus()。
无论如何,基本思想是使用终结点(例如)处理所有错误
/error,并在对应的HTTP状态代码的情况下抛出这些预定义的异常:
@Controllerpublic class CustomErrorController extends AbstractErrorController { private static final String ERROR_PATH= "/error"; @Autowired public CustomErrorController(ErrorAttributes errorAttributes) { super(errorAttributes); } @ExceptionHandler(NotFoundException.class) public String notFound() { return "404"; } @RequestMapping(ERROR_PATH) public ResponseEntity<?> handleErrors(HttpServletRequest request) { HttpStatus status = getStatus(request); if (status.equals(HttpStatus.NOT_FOUND)) throw new NotFoundException(); return ResponseEntity.status(status).body(getErrorAttributes(request, false)); } @Override public String getErrorPath() { return ERROR_PATH; }}当然,此解决方案仅适用于 传统部署
。如果您打算使用嵌入式Servlet容器,则最好定义一个
EmbeddedServletContainerCustomizer。



