控制层统一异常处理

1.定义异常处理类

import com.yy.common.ReturnResult;
import com.yy.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

@RestControllerAdvice
@Slf4j
public class BaseExceptionHandler {

    @ExceptionHandler(value = BaseException.class)
    public ReturnResult baseExceptionHandler(BaseException e) {
        log.error("{}", e);
        return ResponseUtils.error(e.getMessage());
    }

    // 捕获自定义异常
    @ExceptionHandler(BusinessException.class)
    public ReturnResult businessException(BusinessException e) {
        log.error("BusinessException:{}", e.getMessage(), e);
        return ResponseUtils.error(e.getMessage());
    }

    // 捕获所有运行时异常
    @ExceptionHandler(RuntimeException.class)
    public ReturnResult runtimeExceptionException(RuntimeException e) {
        log.error("RuntimeException:{}", e.getMessage(), e);
        return ResponseUtils.error(e.getMessage());
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public ReturnResult paramCheckExceptionHandler(IllegalArgumentException e) {
        log.error("参数校验异常: {}", e);
        return ResponseUtils.error(e.getMessage());
    }

    @ExceptionHandler(value = {MultipartException.class})
    public ReturnResult multipartException(MultipartException ex) {
        String msg = "";
        if (ex.getRootCause() instanceof FileUploadBase.FileSizeLimitExceededException) {
            msg = "上传文件过大[单个文件大小不得超过100M]";
        } else if (ex.getRootCause() instanceof FileUploadBase.SizeLimitExceededException) {
            msg = "上传文件过大[总上传大小不得超过100M]";
        } else {
            msg = "文件上传失败[服务器异常]";
        }
        log.error(msg, ex);
        return ResponseUtils.error(msg);
    }

    @ExceptionHandler(value = Exception.class)
    public ReturnResult exceptionHandler(Exception e) {
        log.error("{}", e);
        return ResponseUtils.error("系统错误");
    }
}

2.定义业务异常类

public class BusinessException extends RuntimeException {

  public BusinessException(String message) {
    super(message);
  }
}

3.服务层 throw new BusinessException(“业务异常”);

此时,前端调用接口报错就会提示 业务异常

备注: @RestControllerAdvice是一个组合注解,由@ControllerAdvice、@ResponseBody组成,而@ControllerAdvice继承了@Component,因此@RestControllerAdvice本质上是个Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值