1. 程式人生 > >SpringBoot定制錯誤的Json數據

SpringBoot定制錯誤的Json數據

自己 tro bool response div str shm includes json數據

(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 }

響應自適應,可以攜帶我們自定義的數據

SpringBoot定制錯誤的Json數據