继承 ErrorController + @ControllerAdvice + @ExceptionHandle 处理一切异常
已知@ControllerAdvice + @ExceptionHandle可以处理 除 404 以外的 运行异常,那么,捕获不到的异常就是404了。
两个类:
NotFoundException
@RestController
public class NotFoundException implements ErrorController {
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping("/error")
public Object error(HttpServletRequest request) {
Map<String, Object> body = new HashMap<>();
body.put("error", "没有找到页面");
body.put("code", "404");
return body;
}
}
ExceptionController
@RestControllerAdvice
public class ExceptionController {
@ExceptionHandler(value = {Exception.class})
public Object error(Exception e){
Map<String,String> map = new HashMap<>();
map.put("error", e.getMessage());
map.put("code", "500");
return map;
}
}