springboot 错误页面的处理机制


typora-root-url: 学习图片

springboot错误页面的处理机制

1.默认状态下:

*页面:

在这里插入图片描述

*json数据:

在这里插入图片描述

2.如何定制错误响应:

原理参照(ErrorMvcAutoConfiguration)

a.DefaultErrorAttributes:

b.BasicErrorController

c.errorPageCustomizer 错误页面响应

d.DefaultErrorViewResolver

步骤:

系统出现4xx 5xx之类的错误,errorPageCustomizer就会生效,就会来到/errro请求,然后通过BasicErrorController处理返回json或者html数据;响应页面是DefaultErrorViewResolver决定的(通过error/状态码 响应)。

1.如何定制错误页面

​ a.有模板引擎情况下:error/状态码.html放在templates下,没有模板引擎,放在静态资源下。

​ b.4xx.html或者5xx.html来适配其他的错误

​ c.页面能获取的信息

​ timestamp:时间戳
​ status:状态码
​ error:错误提示
​ exception:异常对象
​ message:异常消息
​ errors:JSR303数据校验的错误都在这里

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
    <h1>status:[[${status}]]</h1>
    <h2>timestamp:[[${timestamp}]]</h2>
</main>

2如何定制json数据

​ a.做一个定制的异常机制

package com.liu.springboot_demo.exception;

public class UserNotExistException extends RuntimeException {
    public UserNotExistException() {
          super("用户不存在");
    }
}

b.定义异常处理器

package com.liu.springboot_demo.handler;

import com.liu.springboot_demo.exception.UserNotExistException;
import com.sun.deploy.net.HttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

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

@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(UserNotExistException.class)
    public String handlerException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
    map.put("code","user.notexist");
    map.put("msg","用户不存在5555");
    request.setAttribute("ext",map);
    //修改状态码
    request.setAttribute("javax.servlet.error.status_code",500);
    //转发到error页面,让它自己适配返回json还是html    
    return "forward:/error";
    }
}

​ c自定义定义返回的json数据

package com.liu.springboot_demo.handler;

import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.stereotype.Component;;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
    public Map<String, Object> getErrorAttributes(WebRequest requestAttributes, boolean includeStackTrace) {
        Map<String,Object> errormap=  super.getErrorAttributes(requestAttributes, includeStackTrace);
        Map<String,Object> map = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
        errormap.put("tag","刘");
        errormap.put("ext",map);
        return errormap;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值