zoukankan      html  css  js  c++  java
  • 自定义全局异常捕获

    原文:http://blog.csdn.net/jinzhencs/article/details/51700009

    第一种:实现HandlerExceptionResolver

    注意:

    • 把错误码 重设成200,不然还是返回的异常信息。
    • 注解@Compoment交由spring创建bean

    之后就能愉快的返回自己的错误码了。 
    或者记录错误日志。

    /**
     * 全局异常捕获
     * @author Mingchenchen
     *
     */
    @Component
    public class GlobleExceptionHandler implements HandlerExceptionResolver {
        private static Logger logger = Logger.getLogger(GlobleExceptionHandler.class);
    
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                Exception ex) {
            if (ex instanceof InvalidParamException) {
                logger.info("GlobleExceptionHandler catch exception : InvalidParamException");
                ModelAndView mv = new ModelAndView();
                /* 使用response返回 */
                response.setStatus(HttpStatus.OK.value()); // 设置状态码
                response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
                response.setCharacterEncoding("UTF-8"); // 避免乱码
                try {
                    response.getWriter().write("你想返回的JSON字符串");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return mv;
            }
            return null;
        }
    
    }

    第二种方法:使用Spring提供的@ControllerAdvice注解

    之前使用这个注解没配置其他的东西,发现没生效。所以没用它。现在重新研究下,因为确实这种写法很棒。比上面的写法漂亮多了。

    示例代码:

    /**
     * 
     * @ClassName: GlobalExceptionHandler
     * @Description: 全局异常处理类
     * @date: 2015年12月21日 下午5:46:13
     */
    @ControllerAdvice
    class GlobalExceptionHandler {
        private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class);
    
        @ResponseStatus(HttpStatus.UNAUTHORIZED)
        @ExceptionHandler(NotAuthorizedException.class)
        public @ResponseBody ErrorMessage handleNotAuthorizedException(Exception e) {
            logger.error(e.getMessage(), e);
            return new ErrorMessage(e.getLocalizedMessage());
        }
    
        @ResponseStatus(HttpStatus.FORBIDDEN)
        @ExceptionHandler(ForbiddenException.class)
        public @ResponseBody ErrorMessage handleForbiddenException(Exception e) {
            logger.error(e.getMessage(), e);
            return new ErrorMessage(e.getLocalizedMessage());
        }
    
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        @ExceptionHandler(DataAccessException.class)
        public @ResponseBody ErrorMessage handleDataAccessException(Exception e) {
            logger.warn(e.getMessage(), e);
            return new ErrorMessage("数据访问错误: " + e.getLocalizedMessage());
        }
    
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        @ExceptionHandler(HttpAccessException.class)
        public @ResponseBody ErrorMessage handleHttpAccessException(Exception e) {
            logger.warn(e.getMessage(), e);
            return new ErrorMessage("访问外部服务错误: " + e.getLocalizedMessage());
        }
    
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        @ExceptionHandler(Exception.class)
        public @ResponseBody ErrorMessage handleException(Exception e) {
            logger.warn(e.getMessage(), e);
            return new ErrorMessage("系统内部错误: " + e.getLocalizedMessage());
        }
    }

    其实大多时候做后端的并不想跳转页面,而是返回错误码,所以我们只需要

    @ResponseStatus(HttpStatus.OK)
        @ExceptionHandler(MyException.class)
        @ResponseBody
        public JSONObject handleMyException(Exception e) {
            logger.warn(e.getMessage(), e);
            return ReturnUtil.format(Message("访问外部服务错误: " + e.getLocalizedMessage()));
        }

    但是之前我写了这个类,并且注解了@ControllerAdvice应该是交由Spring管理了就OK了,但是不起作用。 
    后续跟进

  • 相关阅读:
    windows 安装 ELK(Elasticsearch,Logstash,kibana)
    NSSM 将程序封装成服务软件
    面试-双向链表
    mySql 事务,游标以及循环
    SQL 事务
    C# Windows 服务
    MVC 中ajax 调用Webservice 或WCF 问题
    js prototype
    计算一个数等于其它数相加的所有可能 如: 5 =1+4 ,1+3+1,2+3,2+2+1,1+1+1+1+1,1+1+1+2
    冒泡排序,选择排序,快速排序
  • 原文地址:https://www.cnblogs.com/shihaiming/p/6101380.html
Copyright © 2011-2022 走看看