码迷,mamicode.com
首页 > 编程语言 > 详细

spring的统一进行异常处理

时间:2018-06-25 19:02:42      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:utils   url   ppi   protected   span   ping   err   统一   char   

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的统一进行异常处理

标签:utils   url   ppi   protected   span   ping   err   统一   char   

原文地址:https://www.cnblogs.com/codechange/p/9225573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!