美文网首页未分类程序员
后端异常统一捕捉

后端异常统一捕捉

作者: alonwang | 来源:发表于2018-04-04 09:43 被阅读0次

    实现 HandlerExceptionResolver ,对自定义异常进行转换,对非自定义异常统一转化为自定义异常并打印日志

    public class BizBusinessExceptionHandler implements HandlerExceptionResolver {
        private static final Logger logger = LogManager.LOGGER.getInstance();
    
        @Override
        public ModelAndView resolveException(HttpServletRequest request,
                HttpServletResponse response, Object o, Exception e) {
            BusinessException exception;
            ErrorRes errorRes;
            if (e instanceof BusinessException) {
                exception = (BusinessException) e;
                errorRes = ErrorRes.builder().errCode(exception.getErrorCode())
                        .errMsg(exception.getMessage()).build();
            } else {
                logger.error("unexpected exception!",e);
                exception = new BusinessException(ErrorCode.SYSTEM_ERROR);
                errorRes = ErrorRes.builder().errCode(exception.getErrorCode())
                        .errMsg(exception.getMessage()).build();
            }
            PrintWriter responseWriter = null;
            try {
                response.setContentType("application/json;");
                response.setCharacterEncoding("UTF-8");
                response.setStatus(Response.SC_OK);
                responseWriter = response.getWriter();
                responseWriter.write(JSON.toJSONString(errorRes));
                responseWriter.flush();
            } catch (IOException e1) {
    
            } finally {
                if (responseWriter != null) {
                    responseWriter.close();
                }
            }
            return new ModelAndView();
        }
    }
    

    相关文章

      网友评论

        本文标题:后端异常统一捕捉

        本文链接:https://www.haomeiwen.com/subject/cfzhhftx.html