JAVA專案做API,SpringMVC攔截異常並返回Json
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
Logger.getLogger(ex.getClass()).error("異常", ex);
// 輸出錯誤Json
ModelAndView mav = new ModelAndView();
MappingJackson2JsonView view = new MappingJackson2JsonView();
Map<String, Object> result = new HashMap<String, Object>();
result.put("Code", -1);
result.put("Message", "處理異常,請稍後再試");
result.put("Data", "");
view.setAttributesMap(result);
mav.setView(view);
return mav;
}
}