springboot自定义全局异常捕获

注意:

  • 把错误码 重设成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()));
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值