SpringBoot利用ControllerAdvice注解捕获全局异常并返回统一格式数据

@RestControllerAdvice

自定义一个类,添加如上注解,此注解相当于同时注解了

@ControllerAdvice  @ResponseBody

添加此注解,本类就支持异常捕获了,我们定义一个方法,在方法上添加注解

@ExceptionHandler(Exception.class)

那么所有异常都会被这个方法捕获,我们可以在方法内定义统一的返回数据了。

我下面写了一个例子

@RestControllerAdvice
public class ControllerException {

    private ErrorResponseBean createErrorBean(int httpStatus, int code, String message, HttpServletRequest request) {
        ErrorResponseBean bean = new ErrorResponseBean();
        bean.setCode(code);
        bean.setHttpStatus(httpStatus);
        bean.setException(message);
        if (null != request) {
            bean.setPath(request.getRequestURI());
        }
        bean.setTimestamp(new Date());
        return bean;
    }

    @ResponseStatus(value = HttpStatus.UNAUTHORIZED) //返回数据时,http返回码
    @ExceptionHandler(UnAuthorizedException.class)
    public ErrorResponseBean handleUnAuthorizedException(UnAuthorizedException exception, HttpServletRequest request) {
        return createErrorBean(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.value(), exception.getMessage(), request);
    }

    /**
     * 处理服务器端数据库处理错误
     */
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({SQLException.class, DataAccessException.class, DataAccessResourceFailureException.class,
            DataException.class, DataIntegrityViolationException.class})
    public ErrorResponseBean handleSQLException(HttpServletRequest request, Exception exception) {
        String message = exception.getLocalizedMessage();
        if (exception.getCause() instanceof ConstraintViolationException) {
            ConstraintViolationException e = (ConstraintViolationException) exception.getCause();
            message = e.getSQLException().getLocalizedMessage();
        }
        return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), message, request);
    }

    /**
     * 处理服务器端其他错误异常
     */
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ErrorResponseBean handleOtherException(HttpServletRequest request, Exception exception) {
        return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage(), request);
    }

}

这个例子中,处理了登录异常(这个Exception是自定义的),数据库异常(包含很多异常),以及其他异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LO嘉嘉VE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值