SpringMVC 拦截异常Exception返回Json,适合Java做后台业务项目

时间:2022-11-18 12:56:06


public class ExceptionHandler implements HandlerExceptionResolver {


@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;
}


}