代码语言: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