SpringBoot之异常处理机制 - Go语言中文社区

SpringBoot之异常处理机制


  1. 自定义异常类:UserNotExistException
    //自定义异常
    public class UserNotExistException extends RuntimeException {
    
        public UserNotExistException() {
            super("用户不存在");
        }
    }

2.异常处理器:MyExceptionHandler

@ControllerAdvice拦截异常,@ExceptionHandler指定处理哪种异常(可指定多个),@ResponseStatus指定返回的http状态码(具体可查看HttpStatus这个类),@ControllerAdvice+@ResponseBody可换成@RestControllerAdvice。注意ControllerAdvice只能捕获到全局Controller范围内的,之外的异常就无法捕获了,如filter中抛出异常的话,ControllerAdvice是无法捕获的。这时候你就需要按照官方文档中的方法,实现 ErrorController并注册为controller。

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码  4xx 5xx   javax.servlet.error.status_code是BasicErrorController里面的变量
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("message","自己定制的message:用户出错啦");
        request.setAttribute("ext",map);
        //转发到/error
        return "forward:/error";
    }
}

3.定制ErrorAttributes

//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
     //返回值的map就是页面和json能获取的所有字段
    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
        map.put("company","com.jlu");
        //我们的异常处理器携带的数据
        Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
        map.put("ext",ext);
        return map;
    }
}

页面打印: (页面能获取的信息;timestamp:时间戳; status:状态码;error:错误提示;exception:异常对象; message:异常消息; errors:JSR303数据校验的错误,ext是自定义信息)
    status:500
    timestamp:Fri Jul 27 20:24:56 CST 2018
    exception:com.jlu.springboot.exception.UserNotExistException
    message:用户不存在
    ext:自己定制的message:用户出错啦
    

4.定制错误页面: 一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error请求;就会被**BasicErrorController**处理;

            1)、有模板引擎的情况下;error/状态码;** 【将错误页面命名为  错误状态码.html 放在模板引擎文件夹里面的 error文件夹下】,发生此状态码的错误就会来到  对应的页面; 我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html);   页面能获取的信息;timestamp:时间戳; status:状态码;error:错误提示;exception:异常对象; message:异常消息; errors:JSR303数据校验的错误都在这里

​            2)、没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;

​            3)、以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;

5、错误页面:5xx.html:

6、请求url,触发用户不存在的异常,返回错误页面

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/kavito/article/details/81253317
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-01 22:47:50
  • 阅读 ( 1010 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢