SpringBoot自定义错误页面追加自定义参数

一.SpringBoot自定义错误页面

可以参考:SpringBoot自定义错误页面

二.追加自定义参数

方式一:完全来编写一个ErrorController的实现类或者是编写AbstractErrorController的子类,放在容器中(比较复杂,不推荐)

方式二:页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到,给容器中加入我们自己定义的ErrorAttributes就可以追加自定义参数

三.方式二举例

1)、定义一个异常类

/**
 * @author hq.zheng
 * @create 2019-03-07-下午 4:47
 */
public class UserNotExistException extends RuntimeException{
    public UserNotExistException() {
        super("用户不存在");
    }
}

2)、定义一个后台请求方法,用来测试异常请求,当发送“/hello?user=zhq”时抛出异常

@ResponseBody
@RequestMapping("/hello")
public String hello(@RequestParam("user") String user){
    if(user.equals("zhq")){
        throw new UserNotExistException();
    }
    return "Hello World!";
}

3)、定义一个ControllerAdvice获取自定义运行时异常,并追加动态异常参数

/**@deprecated 异常处理
 * @author hq.zheng
 * @create 2019-03-07-下午 4:58
 */
@ControllerAdvice
public class MyExceptionHandler {
    //处理用户不存在异常(无法识别是浏览器还是其他客户端,全部都返回json)
    /*@ExceptionHandler(UserNotExistException.class)
    @ResponseBody
    public Map<String,Object> handleException(Exception e){
        Map<String,Object> map=new HashMap<>();
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        return map;
    }*/

    //处理用户不存在异常
    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e,HttpServletRequest request){
        //Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        //定义异常状态码,不定义的话,会认为是正常成功请求200
        request.setAttribute("javax.servlet.error.status_code",400);
        Map<String,Object> map=new HashMap<>();
        //追加错误信息
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        request.setAttribute("ext",map);
        //转发到springboot默认处理异常的控制类
        return "forward:/error";
    }
}

4)、定义一个ErrorAttributes注入到容器中,来处理追加过来的异常参数

/**@deprecated 自定义错误信息
 * @author hq.zheng
 * @create 2019-03-07-下午 5:42
 */
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
    //返回值的map就是页面和json能获取的所有字段
    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
        //追加固定值
        errorAttributes.put("company","zhq");
        //动态追加异常处理器携带的数据
        Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext",0);
        errorAttributes.put("ext",ext);
        return errorAttributes;
    }
}

5)、发送“http://localhost:8080/hello?user=zhq”,用PostMan测试结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值