springboot统一异常处理

本文介绍了一个Spring Boot应用中自定义异常处理和错误属性的方法。通过@ControllerAdvice注解的MyExceptionHandler类处理BizException异常,返回特定的HTTP状态码和错误信息。同时,通过自定义MyErrorAttributes类,增强错误信息的细节,使其更易于理解和调试。
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {
		Integer code = RespCode.RespEnum.SYSERROR_PERMISSIONS_403.getCode();
       String message = RespCode.RespEnum.SYSERROR_PERMISSIONS_403.getDescribe();

    @ExceptionHandler(BizException.class)
    public String handlerBizException(BizException e, HttpServletRequest request, HttpServletResponse response){
        log.debug("MyExceptionHandler.handlerBizException>>>>>>>>>>>>>>>>>>>>>>>>>>");
       //此处使用对象或map集合均可以
        RespData bizException = new RespData();
        bizException .setRespInfo(false,code, message);

	// Map<String,Object> bizException = new HashMap<>();
	// bizException .put("code",e.getCode());
	// bizException .put("message",e.getMessage());
        request.setAttribute("bizException ",bizException );
        //  request.setAttribute("javax.servlet.error.status_code",500);
        request.setAttribute("javax.servlet.error.status_code",e.getCode());

	// 判断请求类型是否为Ajax请求
        String header = request.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
        if(isAjax){
            JSONObject object = new JSONObject();
            object.put("code", e.getCode());
            object.put("message", e.getMessage());
            this.returnJson(response, object.toJSONString());
        }
        //转发到/error
        return "forward:/error";
    }
    private void returnJson(HttpServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}

@Component
@Slf4j
public class MyErrorAttributes extends DefaultErrorAttributes {

    //返回值的map就是页面和json能获取的所有字段
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        log.debug("MyErrorAttributes.getErrorAttributes>>>>>>>>>>>>>>>>>>>>>>>>>>");
        Map<String, Object> errorAttributesMap=super.getErrorAttributes(webRequest, includeStackTrace);
        //添加需要返回的信息
        //异常处理器携带的数据 ,注意当bizException在页面获取不到值时,会再次发出请求
        Object bizException = webRequest.getAttribute("bizException",0);
        if(StringUtil.isObjectNotEmpty(bizException))
            errorAttributesMap.put("bizException",bizException);
        return errorAttributesMap;
    }
}

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(@RequestParam("user") String user){
        if(user.equals("aa")){
            try{
                int a=0/0;
            }catch (Exception e){
                throw new BizException("502","测试111");
//                throw new BizLoginException("501","测试登录111");
            }

        }
        return "hello world test";
    }
http://127.0.0.1:8080/sys/hello?user=aa
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值