一:覆盖默认的异常处理
覆盖默认的异常处理有两种方式
- BasicErrorController 方式
- @ExceptionHandler 注解方式
在Spring boot开发中经常遇到“Whitelabel Error Page”白色标签错误页,这个页面当spring boot中发生错误时的默认处理方式,返回一个error页面,而这个页面的格式是固定的,这个页面有几个变量,映射地址:/error, status=404,type=Not Found。
SpringBoot的默认错误处理是BasicErrorController,支持两种格式:
- 错误页面 errorHtml
- json响应 error


@Controller@RequestMapping("${server.error.path:${error.path:/error}}")public class BasicErrorController extends AbstractErrorController {private final ErrorProperties errorProperties;@RequestMapping(produces = "text/html")public ModelAndView errorHtml(HttpServletRequest request,HttpServletResponse response) {HttpStatus status = getStatus(request);Map model = Collections.unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));response.setStatus(status.value());ModelAndView modelAndView = resolveErrorView(request, response, status, model);return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);}@RequestMapping@ResponseBodypublic ResponseEntity> error(HttpServletRequest request) {Map body = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.ALL));HttpStatus status = getStatus(request);return new ResponseEntity<>(body, status);}}
二:自定义错误处理BasicErrorController方式
1、 MyErrorController继承BasicErrorController
@Controllerpublic class MyErrorController extends BasicErrorController{ public MyErrorController(ServerProperties serverProperties) { super(new DefaultErrorAttributes(), serverProperties.getError());} @Overridepublic ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); response.setStatus(status.value()); Map model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);} @Overridepublic ResponseEntity> error(HttpServletRequest request) { HttpStatus status = getStatus(request); Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); //输出自定义的Json格式 Map map = new HashMap<>(); map.put("success", false); map.put("msg", body.get("message")); return new ResponseEntity<>(map, status); }}
2、error.html
将自定义的error.html放在src/main/resources/templates下
这里的error.html是在网上随意找的。


三:自定义错误处理 @ExceptionHandler注解方式
@ExceptionHandler的value定义的是要匹配的异常类型,这里写了一个总的异常Exception,可以针对某个具体的异常进行处理。
GlobalExceptionHandler
@ControllerAdviceclass GlobalExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "error"; // errorHtml@ExceptionHandler(value = Exception.class)public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav;}// error json@ExceptionHandler(value = NullPointerException.class)@ResponseBodypublic Map defaultJSONErrorHandler(HttpServletRequest req, Exception e) throws Exception { /* 实际使用一般返回这种格式{"success": true,"code": 200,"msg": "成功","result": {}}*/ Map res = new HashMap<>(); res.put("exception", e); res.put("url", req.getRequestURL()); return res; }}
SampleController
@Controllerpublic class SampleController { @GetMapping("/index") public ModelAndView index(Model model, HttpServletRequest request){ ModelAndView modelAndView = new ModelAndView("index"); if (1==1) { throw new IllegalArgumentException("error paramaters"); } return modelAndView; }}
@RestControllerpublic class TestController { @GetMapping("/test") public String test(){ if (1==1) { throw new NullPointerException("null"); } return null; }}
src/main/resources/templates/error.html
统一异常处理
Error Handler

