spring的统一进行异常处理
public class ExceptionHandler extends SimpleMappingExceptionResolver { private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class); @Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = super.doResolveException(request, response, handler, ex); String url = WebUtils.getPathWithinApplication(request); logger.error("controller error.url=" + url, ex); /* 使用response返回 */ response.setStatus(HttpStatus.OK.value()); // 设置状态码 response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType response.setCharacterEncoding("UTF-8"); // 避免乱码 response.setHeader("Cache-Control", "no-cache, must-revalidate"); JsonResult jsonResult=new JsonResult(JsonResultCode.FAILURE,"系统错误,请联系管理员",""); if(ex instanceof ServiceException) { ServiceException serviceException=(ServiceException)ex; String code=serviceException.getCode(); String message=serviceException.getMessage(); jsonResult=new JsonResult(code,message,""); } try { PrintWriter printWriter = response.getWriter(); printWriter.write(JSONObject.fromObject(jsonResult).toString()); printWriter.flush(); printWriter.close(); } catch (IOException e) { logger.error("与客户端通讯异常:" + e.getMessage(), e); } logger.error("异常:" + ex.getMessage(), ex); return mv; } }
在spring的配置文件加上 <bean id="exceptionHandler" class="xxx.xxx.xxx.ExceptionHandler"/>
第二种方式,基于HandlerExceptionResolver接口方式
@Component public class MyHandlerExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) { //是否为ajax请求 String requestType = request.getHeader("X-Requested-With"); if(exception instanceof AuthorizationException){ response.setStatus(413);//无权限异常 主要用于ajax请求返回 response.addHeader("Error-Json", "{\"code\":413,\"msg\":\"nopermission\"}"); response.setContentType("text/html;charset=utf-8"); if("XMLHttpRequest".equals(requestType)){ return new ModelAndView(); } return new ModelAndView("redirect:/html/413.html"); } return null; } }
该方法返回一个ModelAndView对象,在方法内部对异常的类型进行判断,然后返回合适的ModelAndView对象,如果该方法返回了null,则spring会
继续寻找其他的实现了HandlerExceptionResolve接口的bean