自定义全局异常捕获

第一种:实现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了,但是不起作用。
后续跟进

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 众所周知,Android程序在运行时遇到未处理的错误,会弹出类似程序异常退出之类的dialog,然后自动关闭。那么...
    MrRock阅读 3,889评论 10 16
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,954评论 6 342
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 1,726评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 古塔区阜康里123楼车棚拆除的工作方案 为有效推进我区双百整治工作,我队决定对位于古塔区阜康里123号楼的...
    王泽er阅读 155评论 0 0