spring mvc @ExceptionHandler 異常處理
spring mvc 統一的異常處理,有兩種方式。
一、exceptionResolver
二、ExceptionHandler
兩者不能同時配置。如果配置了第一種,則第二種無效。就因為這個原因,找了一天的問題。
ExceptionHandler 通過注解的方式,進行配置,只需要在某個controller 中設置了這個注解,則這個controller中的所有異常都會通過這個方法進行處理。
比如rest controller,增加一個
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
Map map = new HashMap();
logger.error("error," + UUID.randomUUID().toString(), ex);
request.setAttribute("ex", ex);
String msg = ex.getMessage();
map.put("success", "0");
map.put("msg", msg);
String rtnjson = JSONUtil.objectToJson(map);
request.setAttribute("json", rtnjson);
return "json";
}
這樣,這個controler中的異常,都會由這個異常處理方法,進行統一處理,生成異常json。避免在各個方法中通過try catch 的方法,進行異常處理。
一、exceptionResolver
二、ExceptionHandler
兩者不能同時配置。如果配置了第一種,則第二種無效。就因為這個原因,找了一天的問題。
ExceptionHandler 通過注解的方式,進行配置,只需要在某個controller 中設置了這個注解,則這個controller中的所有異常都會通過這個方法進行處理。
比如rest controller,增加一個



















這樣,這個controler中的異常,都會由這個異常處理方法,進行統一處理,生成異常json。避免在各個方法中通過try catch 的方法,進行異常處理。
posted on 2016-11-08 08:32 風人園 閱讀(394) 評論(0) 編輯 收藏 所屬分類: Spring