标签:erro obj over Servle return 解析 for boot ret
(1)自定义异常处理&返回定制Json数据
1 @ControllerAdvice 2 public class MyExceptionHandler { 3 @ResponseBody 4 @ExceptionHandler(UserNotExistException.class) 5 public Map<String,Object> handleException(Exception e){ 6 Map<String,Object> map = new HashMap<>(); 7 map.put("code",404); 8 map.put("message",e.getMessage()); 9 return map; 10 } 11 }
缺点:没有自适应效果,只是会返回自定义的json数据
(2)
1 @ControllerAdvice 2 public class MyExceptionHandler { 3 @ExceptionHandler(UserNotExistException.class) 4 public String handleException(Exception e, HttpServletRequest request){ 5 //Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); 6 //传入我们自己的错误状态码,4xx,5xx,否则不会进入定制错误页面的解析流程 7 request.setAttribute("javax.servlet.error.status_code",500); 8 Map<String,Object> map = new HashMap<>(); 9 map.put("code",404); 10 map.put("message",e.getMessage()); 11 return "forward:/error"; 12 } 13 }
缺点:可以自适应页面(浏览器返回错误页面,客户端返回Json数据),但不会携带我们自定义数据
(3)
1 public class MyErrorAttributes extends DefaultErrorAttributes { 2 @Override 3 public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { 4 Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace); 5 map.put("msg","coreqi"); 6 return map; 7 } 8 }
响应自适应,可以携带我们自定义的数据
标签:erro obj over Servle return 解析 for boot ret
原文地址:https://www.cnblogs.com/fanqisoft/p/10324837.html