spring的统一进行异常处理
Posted kankankankankan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"/>
以上是关于spring的统一进行异常处理的主要内容,如果未能解决你的问题,请参考以下文章