目的与原理:
处理异常时,若我们想根据实际情况返回不同的页面,@ControllerAdvice与@ExceptionHandler,一般用于处理应用级别的异常,一些容器级别的错误就处理不了,例如Filter中抛出异常,SpringBoot对于错误会有一个默认页面给用户显示出来,现在我们想显示自己的页面。
SpringBoot在返回错误信息时不一定返回HTML页面,而是根据实际情况返回HTML或者一段JSON,我们可以将这二者自己定制。
SpringBoot中的错误默认是由BasicErrorController类来处理的,这个类核心方法有两个:
@Controllerpublic class MyErrorController extendsBasicErrorController {
@AutowiredpublicMyErrorController(ErrorAttributes errorAttributes,
ServerProperties serverProperties,
ListerrorViewResolvers) {super(errorAttributes, serverProperties.getError(), errorViewResolvers);
}
@OverridepublicModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status=getStatus(request);
Map model =getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
model.put("custommsg", "出错啦!");
ModelAndView modelAndView= new ModelAndView("myErrorPage", model, status);returnmodelAndView;
}
@Overridepublic ResponseEntity>error(HttpServletRequest request) {
Map body =getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
body.put("custommsg", "出错啦!");
HttpStatus status=getStatus(request);return new ResponseEntity<>(body, status);
}
}
errorHtml方法用来返回错误HTML页面,error用来返回错误json,这两个究竟返回哪个,看请求头Accept参数。首先看返回HTML页面的errorHTML方法,通过调用resolveErrorView方法来获取一个ModelAndView。而resloveErrorView方法的调用最终会来到DefaultErrorViewResolver类中,这个类是SpringBoot中默认的错误信息视图解析器。
从DefaultErrorViewResolver类的部分源码中看到,SpringBoot默认是在error目录下查找4xx,5xx的文件作为错误视图,当找不到会回到errorHtml方法中,然后使用error作为默认的错误页面视图名,如果没有名字是error的页面,就会以默认的错误页面显示。
1.简单配置:
controller:
如果我们只是简单使用,直接在/static/error/下创建4xx.html,5xx.html的页面即可,也可以使用响应码直接命名文件若404.html,500.html。
这样只能使用静态HTML页面,无法向用户展示完整的错误信息,使用我们要用模板语言,比如用Thymeleaf模板语言为例,Thymeleaf默认处于classpath:/templates/目录下,如图:
4xx.html
Titletimestampstatuserrormessagepath