idea的自定义错误页面

2 篇文章 0 订阅

模板引擎的情况下;error/状态码; 【将错误页面命名为  错误状态码.html 放在模板引擎文件夹即templates里面的 error文件夹下】,发生此状态码的错误就会来到  对应的页面;

页面能获取的信息;

timestamp:时间戳

status:状态码

error:错误提示

exception:异常对象

message:异常消息

errors:JSR303数据校验的错误都在这里

IDEA为2.xx 版本  配置文件中添加

#获取错误信息server.error.include-exception=trueserver.error.include-message=always

5xx.html错误页面可获取参数 代码:

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
   <h1>status:[[${status}]]</h1>//行内写法
   <h1>timestamp:[[${timestamp}]]</h1>
   <h1>error:[[${error}]]</h1>
   <h1>exception:[[${exception}]]</h1>
   <h1>message:[[${message}]]</h1>
   <h1>message:[[${ext.code}]]</h1>
</main>

@ControllerAdvice //异常处理 标注MyExceptionHandler.Class 为异常处理类

@ControllerAdvice //异常处理
public class MyExceptionHandler {

    //第一种:浏览器客户端都是返回json数据
//    @ResponseBody //将数据json格式发送到页面显示
//    @ExceptionHandler(UserNotExistException.class)//指定处理的异常
//    public Map<String,Object> handleException(Exception e){
//        Map<String,Object> map = new HashMap<>();
//        map.put("code","user not");
//        map.put("message",e.getMessage());
//        return map;
//    }

//第二种:浏览器返回页面,客户端返回json数据
    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码  4xx 5xx,否则就不会进入定制错误页面的解析流程
        /**
         * Integer statusCode = (Integer) request
         .getAttribute("javax.servlet.error.status_code");
         */
         //指定错误码为500触发相应的错误页面及设定的参数
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        request.setAttribute("ext",map);
        //转发到/error
        return "forward:/error";
    }
}

@Component 相当于加入一个ben到容器中 标注 MyErrorAttributes.Class中

//给容器中加入自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> map = super.getErrorAttributes(webRequest, options);
        map.put("company","atguigu");//公司名称atguigu
        //我们的异常处理器携带的数据
        Map<String,Object> ext = (Map<String,Object>)webRequest.getAttribute("ext", 0);
        map.put("ext",ext);
        return map;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值