springboot随笔四:自定义error page

springboot的自动配置在ErrorMvcAutoConfiguration实现

org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration

大致原理:

当发生exception时,由ErrorPageCustomizer发出请求转发/error,
放出的/error请求,请求由BasicErrorController接受,BasicErrorController会根据请求头中不同的Accept来由不同的方法处理,然后返回error status对应的页面,

 

 

 

 

方法一:根据springboot的默认配置,在error文件夹下添加相关的error页面,如有模板页返回模板页(如:/template/error/404.html),否则返回静态页(/static/error/404.html)

 

/template/error/404.html和/static/error/404.html(若找不到会找4xx.html)同时存在时返回/template/error/404.html(若找不到会找4xx.html),

 

可以在模板页面中取出默认置入的一些数据,/template/error/404.html==>

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>404</title>
</head>
<body>
template 404<br/>
[[${status}]]<br/>
[[${error}]]<br/>
[[${path}]]<br/>
</body>
</html>

 

 

 

方法二:使用@ControllerAdvice   +   @ExceptionHandler

 

 

package com.wzp.advice;

import com.wzp.UserException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice// 对所有的controller进行增强
public class MyControllerAdvice {

    // 当发生异常时,进行统一处理
    @ExceptionHandler(value = {Exception.class})
    public String handleException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("message", e.getMessage());
        map.put("code", e.getMessage());
        request.setAttribute("javax.servlet.error.status_code", 500);// 设置状态码
        return "forward:/error";// 将请求交给springboot的默认error处理器
    }

    @ExceptionHandler(value = {UserException.class})
    public String handleUserException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("message", e.getMessage());
        map.put("code", e.getMessage());
        request.setAttribute("javax.servlet.error.status_code", 555);// 设置状态码
        return "forward:/error";// 将请求交给springboot的默认error处理器
    }

}

 

posted @ 2020-12-22 11:12  卖麦的麦麦  阅读(912)  评论(0)    收藏  举报