异常处理
处理异常时会用到三个错误页面分别为:
- 404页面
- 500页面
- error页面
一.定义异常错误页面
在Springboot中遇到异常会自动跳到一个统一的异常页面,这意味着Springboot已经有一套处理异常的机制,我们只需要自己去定义该错误的页面。
SpringBoot 默认的异常处理机制:一旦程序中出现了异常 SpringBoot 就会请求 /error 的 url ,然后跳转到默认显示异常的页面来展示异常信息。接下来就是自定义异常错误页面了,方法很简单,就是在目录 src/main/resources/templates/ 下定义一个error文件夹,放入404.html,500.html就可以了。
文件结构:
这样当出现404,500错误时就会跳转
error页面定义
这里需要一个自定义异常类
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
public NotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
这里使用了ResponseStatus注解,我们自定义的异常可以在页面上显示
下面需要一个拦截器
@ControllerAdvice
public class ControllerExceptionHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHander(HttpServletRequest request, Exception e){
logger.error("Request URL : {}, Exception : {} ", request.getRequestURL(), e);
if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
//通过注解工具类判断是否有状态码
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
}
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("url", request.getRequestURL());
modelAndView.addObject("exception", e);
modelAndView.setViewName("error/error");
return modelAndView;
}
}
这里使用拦截器进行统一的异常处理,通过AnnotationUtils.findAnnotation()判断是否有状态吗,当存在状态码时,则抛出异常,不存在时则返回error页面
错误页面异常信息处理
<div>
<div th:utext="'<!--'" th:remove="tag"></div>
<div th:utext="'Failed Request URL : ' + ${url}" th:remove="tag">
</div>
<div th:utext="'Exception message : ' + ${exception.message}"
th:remove="tag"></div>
<ul th:remove="tag">
<li th:each="st : ${exception.stackTrace}" th:remove="tag"><span
th:utext="${st}" th:remove="tag"></span></li>
</ul>
<div th:utext="'-->'" th:remove="tag"></div>
</div>