SpringBoot : 全局异常配置

时间:2022-07-24
本文章向大家介绍SpringBoot : 全局异常配置,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
@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