首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >SpringBoot : 全局异常配置

SpringBoot : 全局异常配置

作者头像
源码之路
发布2020-09-03 09:42:25
发布2020-09-03 09:42:25
7170
举报
文章被收录于专栏:源码之路源码之路
代码语言:javascript
复制
@ControllerAdvice
public class AllException {
    @ExceptionHandler(Exception.class)
    public void exception(Exception e, HttpServletResponse response) throws IOException {
        response.setContentType ("text/html;charset=utf-8");
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode root = mapper.createObjectNode();//创建一个根对象
        root.put("code", 900);
        root.put("msg", e.getMessage());
        root.put("level", "应用级异常");
        PrintWriter out = response.getWriter();
        out.write(root.toString());
        out.flush();
        out.close();
    }   
}

image.png

但是这种异常只能处理应用级别的异常,容器级别的异常就处理不了了,比如OutOfMemorryException,如何处理呢? 详见如下代码:

代码语言:javascript
复制
@Component
public class MyErrorAttribute extends DefaultErrorAttributes {

    @Override
    public Map<String , Object> getErrorAttributes(WebRequest webRequest , boolean
            includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest,
                includeStackTrace);
        //封装成自定义的字段,去掉系统默认字段
        errorAttributes.put("code",errorAttributes.get("status"));
       errorAttributes.put("msg",errorAttributes.get("message"));
       errorAttributes.put("level","系统级异常");
        errorAttributes.remove("error");
        errorAttributes.remove("message");
        errorAttributes.remove("status");
        return errorAttributes;
    }
}

image.png

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档