SpringBoot全局异常处理,代码更优雅

转自:今日头条作者【瞎胡佛https://www.toutiao.com/i6898572122302513676/?tt_from=weixin&utm_campaign=client_share&wxshare_count=1&timestamp=1607903554&app=news_article&utm_source=weixin&utm_medium=toutiao_android&use_new_style=1&req_id=202012140752340101300361404DF616E4&group_id=6898572122302513676

全局异常处理

创建一个 GlobalExceptionHandler 类,使用 @RestControllerAdvice(增强型控制器) 注解就可以定义出异常通知类,默认只会处理controller层抛出的异常,如果需要处理service层的异常,我们可以自定义自己的异常类,进行捕捉

我们在在定义的方法中添加上 @ExceptionHandler 即可实现全局异常异常的捕

ControllerAdvice 和 RestControllerAdvice的区别

@ControllerAdvice 和 @RestControllerAdvice都是对Controller进行增强的,可以全局捕获spring mvc抛的异常。

@RestControllerAdvice = ControllerAdvice + ResponseBody

spring官方文档 主要配合@ExceptionHandler使用,统一处理异常情况

技术干货!SpringBoot全局异常处理,代码更优雅

 

/**
 * controller 异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result handlerImCustomException(CustomException e) {
        log.error("自定义异常:{}", e.getMessage(), e);
        return new Result().buildFail(e);
    }

    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常,详情继续往下看代码
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        log.error("请求校验异常 BindException message:{} exception:{}", message, e.getMessage(), e);
        return new Result().buildFail(message);
    }

    /**
     * 处理参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {

        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        log.error("校验参数异常 message:{} exception:{}", message, e.getMessage(), e);
        return new Result().buildFail(message);
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handlerConstraintViolationException(ConstraintViolationException e) {
        String message =
                e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        log.error("校验参数异常 message:{} exception:{}", message, e.getMessage(), e);
        return new Result().buildFail(message);
    }

    /**
     * 其他异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handler(Exception e) {
        log.error("系统异常", e);
        return new Result().buildFail(CustomExceptionEnum.FAIL);
    }

}

###总结结

通过@RestControllerAdvice源码分析,@ControllerAdvice和@ResponseBody的合并。此注解通过对异常的拦截实现的统一异常返回处理,如果大家在项目中有类似的需求,写作不易,点个赞再走呗~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值