SpringBoot 全局异常处理

1年前 (2023) 程序员胖胖胖虎阿
107 0 0

SpringBoot 全局异常处理

在我们写项目时候,肯定会遇到各种各样的异常报错和用户传值错误需要返回对应的错误提示,如果我们都手动进行返回Result对象的话就会出现两个比较麻烦的问题:

  1. 各种的异常无法返回Result对象,一旦报错就会直接在前端显示500的报错信息(除非你对于所有会报错的语句都进行try/catch捕捉),并且可以网络中看到对应的报错信息,如果你是自己的项目可能没有什么事情,但是如果是公司项目的话就会有很大的问题,因为500的报错信息中携带你部分的代码和你class文件的目录结构。

  2. 很多时候用户输入的信息并不规范,我们后端对于用户输入的所有信息都进行判断,然而这些判断基本上都是写的业务层(service层)中的,我们不能直接返回对应错误的Result,需要返回一个固定的code,然后再在controller层中对于code进行判断,不同的code就返回不同的Result,这个方法一旦判断的条件多起来之后就会异常麻烦,有时候还会忘记code所对应的错误。

所以在大项目中使用全局异常处理,是很有必要的!

实操

1、自定义一个实体类

@Getter
public class BusinessException extends RuntimeException {
    private final int code;

    private final String description;

    public BusinessException(String message, int code, String description) {
        super(message);
        this.code = code;
        this.description=description;
    }
    public BusinessException(ResultCode resultCode, String description) {
        super(resultCode.getMsg());
        this.code = resultCode.getCode();
        this.description=description;
    }
}

2、定义一个全局异常捕捉类

@RestControllerAdvice
@Component
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResultUtil businessExceptionHandler(BusinessException e){
        log.error("BusinessException:{}",e);
        return ResultUtil.failed(e.getCode(),e.getMessage(),e.getDescription());
    }

    @ExceptionHandler(RuntimeException.class)
    public ResultUtil runtimeExceptionHandler(RuntimeException e){
        log.error("RuntimeException:{}",e);
        return ResultUtil.failed(ResultCode.SYSTEM_ERROR,e.getMessage());
    }
}

这样我们系统总所有的BusinessExceptionRuntimeException就都会被这个类捕捉,并统一返回Result给前端

例如:

        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException("格式错误",500,"用户名或密码为空");
        }

版权声明:程序员胖胖胖虎阿 发表于 2023年3月21日 上午10:32。
转载请注明:SpringBoot 全局异常处理 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...