1 自定義異常返回json數據、java
//不要忘記添加 @ControllerAdviceweb
@ControllerAdvicejson
public class myExceptionHandler {瀏覽器
//瀏覽器和客戶端返回的都是json // @ResponseBody
@ExceptionHandler(UserNotExist.class)session
public Map<String ,Object> handlerException(Exception e){ Map<String,Object> map = new HashMap<>(); map.put("code","user.notexist"); map.put("message",e.getMessage()); return map;
} }this
2 轉發到/error下,進行自適應響應 @ControllerAdvice public class myExceptionHandler {code
//瀏覽器和客戶端返回的都是json @ExceptionHandler(UserNotExist.class) public String handlerException(Exception e, HttpServletRequest request){ Map<String,Object> map = new HashMap<>(); request.setAttribute("javax.servlet.error.status_code",500); map.put("code","user.notexist"); map.put("message",e.getMessage()); request.setAttribute("ext",map); return "forward:/error"; }
}rem
3 將定製的錯誤攜帶出去 @Componentget
public class myErrorAtrributes extends DefaultErrorAttributes {servlet
//WebRequest webRequest,注意1.x.x版本的寫法與2.1.0寫法不一樣,個人是2.1.0 public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest,includeStackTrace); errorAttributes.put("com", "maodong"); Map<String,Object> ext= (Map<String, Object>) webRequest.getAttribute("ext",0); errorAttributes.put("ext",ext); return errorAttributes; }
}
//爲啥這麼寫:父類DefaultErrorAttributes類中的方法
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes = new LinkedHashMap(); errorAttributes.put("timestamp", new Date()); this.addStatus(errorAttributes, webRequest); this.addErrorDetails(errorAttributes, webRequest, includeStackTrace); this.addPath(errorAttributes, webRequest); return errorAttributes; } //爲啥WebRequest webRequest能獲得與低版本RequestAttrributes相同的結果 public interface WebRequest extends RequestAttributes { @Nullable String getHeader(String var1); @Nullable String[] getHeaderValues(String var1); Iterator<String> getHeaderNames(); ------ } //爲啥 Map<String,Object> ext= (Map<String, Object>) webRequest.getAttribute("ext",0);能得到ext public interface RequestAttributes { int SCOPE_REQUEST = 0; int SCOPE_SESSION = 1; String REFERENCE_REQUEST = "request"; String REFERENCE_SESSION = "session"; @Nullable Object getAttribute(String var1, int var2); void setAttribute(String var1, Object var2, int var3); void removeAttribute(String var1, int var2);