前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot : 全局异常配置

SpringBoot : 全局异常配置

作者头像
源码之路
发布2020-09-03 09:42:25
4400
发布2020-09-03 09:42:25
举报
文章被收录于专栏:源码之路源码之路源码之路
@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,如何处理呢? 详见如下代码:

@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 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档