Spring Boot----错误页面处理

原理:略

定制错误html页面

在有thymeleaf模板引擎下:

1、在template下创建error目录,在error目录中,创建404.html页面,如果发生错误代码为404,就会去找这个页面(可以创建所有的状态码页面)

2、在error目录中,创建4xx.html页,如果找不到对应的状态码页面,就会去找4xx.html页面(注意4xx.html就是4xx)

<body>
获取时间戳                [[${timestamp}]]  <br/>
获取状态码                [[${status}]]     <br/>
获取错误信息              [[${error}]]      <br/>
获取异常对象              [[${exception}]]  <br/>
获取异常信息              [[${message}]]    <br/>
JSR303数据验证错误        [[${errors}]]     <br/>
</body>

在没有thymeleaf模板引擎下:

在static下创建error目录,在error目录中,创建404.html页面,如果发生错误代码为404,就会去找这个页面(可以创建所有的状态码页面)

只是不能 [[${timestamp}]] 通过这样获取错误信息了

定制错误json数据

application.properties (SpringBoot 2.x),如果没有特殊需求,默认false也是可以的

server.error.include-exception=true  //保证 [[${exception}]] 可以获取到数据

  

1、创建自定义错误对象

public class Myexception extends RuntimeException {
    public Myexception() {
        super("错误消息");
    }
}

2、contoller

@RequestMapping(value = "userlist")
public String userlist(){
        if (true){
            throw new Myexception();  //模拟服务器发生错误
        }
}

3.1如果抛出服务器错误没有被处理,就会返回5xx.html文件

5xx.html

<body>
获取时间戳                [[${timestamp}]]  <br/>
获取状态码                [[${status}]]     <br/>
获取错误信息              [[${error}]]      <br/>
获取异常对象              [[${exception}]]  <br/>  //可以获取到异常的对象了
获取异常信息              [[${message}]]    <br/>  //可以获取到异常的消息了
JSR303数据验证错误        [[${errors}]]     <br/>
</body>

3.2 处理服务器抛出的错误,直接返回一个json数据,上面配置的html失效(注意:此时浏览器和客户端返回的都是json数据)

@ControllerAdvice
public class MyExceptionHandler {
    @ResponseBody
    @ExceptionHandler  //@ExceptionHandler(MyException.class)处理某一个错误
    public Map<String,Object> handleException(Exception e){
        Map<String, Object> map = new HashMap<>();
        map.put("code",400);
        map.put("message","请求出现错误");
        return map;
    }
}

3.3 如果需要浏览器访问返回html,客户端返回json

@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler
    public String handleException(Exception e, HttpServletRequest request){
        //重定向到/error的时候需要手动设置状态码,默认javax.servlet.error.status_code=200
        request.setAttribute("javax.servlet.error.status_code",404);

        //可以给MyErrorAttributes传入数据;
        Map<String, Object> map = new HashMap<>();
        request.setAttribute("map",map);
        return "forward:/error";
    }
}

@Component
class MyErrorAttributes extends DefaultErrorAttributes{
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        //如果不需要自带的错误返回消息,可以不用继承,自己new LinkedHashMap<>();返回它就可以了
        Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);


        //可以直接创建数据
        map.put("code",404);
        map.put("message","请求错误");

        //可以从handleException中获取数据
        Object map1 = webRequest.getAttribute("map", 0);
        map.put("map1",map1);
        return map;
    }
}

  

猜你喜欢

转载自www.cnblogs.com/yanxiaoge/p/11364752.html