拒绝 try-catch:如何设计全局通用的异常拦截体系?

前言

在实际开发中,业务逻辑异常(如余额不足、权限受限)或系统异常(如空指针、数据库连接超时)无处不在。如果任由异常向上抛出,前端将会接收到含糊的 500 错误或敏感的代码堆栈信息。

我们不需要在每个 Controller 方法中写 try-catch,而是通过 @RestControllerAdvice 建立一套全局拦截机制,将所有捕获到的异常,统一转化为上一篇定义的 Result 响应体返回。

定义业务异常类

对于业务类异常,我们需要明确告知调用方具体的错误编码和提示信息。因此,在自定义业务异常(BusinessException)时,必须包含 code 字段,而 message 则直接复用父类 RuntimeException 的消息体系。

核心逻辑:

  • code :对应 Result 实体中的业务状态码,用于前端逻辑判断。
  • message:描述具体的异常原因,用于前端友好提示。

通过这种方式,我们可以将异常直接转化为标准化的 Result 响应。

这里我们用到上一节定义的 ResultCode 相关类来构建业务异常,# 手把手带你封装生产级 Result 实体

java 复制代码
@Getter
public class BusinessException extends RuntimeException {

    private final int code;

    /**
     * 使用默认错误码(1)构造
     *
     * @param message 错误信息
     */
    public BusinessException(String message) {
        super(message);
        this.code = CommonResultCode.BUSINESS_ERROR.getCode();
    }

    /**
     * 使用结果码接口构造
     *
     * @param resultCode 结果码接口
     */
    public BusinessException(ResultCode resultCode) {
        super(resultCode.getMessage());
        this.code = resultCode.getCode();
    }

    /**
     * 使用结果码接口构造,但覆盖错误信息
     *
     * @param resultCode 结果码接口
     * @param message    错误信息
     */
    public BusinessException(ResultCode resultCode, String message) {
        super(message);
        this.code = resultCode.getCode();
    }

    /**
     * 指定错误码构造
     *
     * @param code    错误码
     * @param message 错误信息
     */
    public BusinessException(int code, String message) {
        super(message);
        this.code = code;
    }

    /**
     * 包装其他异常
     *
     * @param message 错误信息
     * @param cause   原始异常
     */
    public BusinessException(String message, Throwable cause) {
        super(message, cause);
        this.code = CommonResultCode.BUSINESS_ERROR.getCode();
    }
}

全局异常处理器

定义好业务异常后,要使其能正常工作,需要配合全局异常处理器一起使用。在全局异常处理其中,除了普通的业务异常外,还要包含其他的如校验、服务器异常、404 等异常的处理:

java 复制代码
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.warn("业务异常: {} {}", request.getRequestURI(), e.getMessage());
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常 (JSON Body)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String message = this.buildBindingResultMsg(e.getBindingResult());
        log.warn("参数校验异常: {} {}", request.getRequestURI(), message);
        return Result.fail(CommonResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理参数绑定异常 (Form Data)
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e, HttpServletRequest request) {
        String message = this.buildBindingResultMsg(e.getBindingResult());
        log.warn("参数绑定异常: {} {}", request.getRequestURI(), message);
        return Result.fail(CommonResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<Void> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.warn("请求方法不支持: {} {}, 支持的方法: {}", request.getMethod(), request.getRequestURI(), e.getSupportedHttpMethods());
        return Result.of(CommonResultCode.METHOD_NOT_ALLOWED);
    }

    /**
     * 处理兜底异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("系统异常: " + request.getRequestURI(), e);
        return Result.of(CommonResultCode.SYSTEM_ERROR);
    }

    private String buildBindingResultMsg(BindingResult result) {
        return result.getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
    }
}

有了这些配置,我们在业务中就可以通过抛异常的方式处理业务异常了!

相关推荐
维克兜率天1 小时前
【维克】ARMA模型:AR与MA的完美结合
后端·restful
是未才2 小时前
从输入 URL 到页面返回:DNS、路由、TLS 与 HTTP 完整链路
java·后端·计算机网络
上海安当技术3 小时前
半天接入:USBKey RESTful API + C 动态库,Web 和 C/S 两套集成路径实战
前端·后端·restful·集成·usbkey
DevUI团队3 小时前
从“即兴创作”到“规格先行”,华为云码道(CodeArts)代码智能体持续深耕企业级规范驱动开发能力
前端·人工智能·后端
weixin_431600444 小时前
NestJS 入门(3):Guard 如何挡住未登录请求?
前端·后端·学习·nest.js
IT_陈寒5 小时前
JavaScript类型转换把我坑惨了,这破玩意真该早点搞明白
前端·人工智能·后端
用户938515635075 小时前
手写一个 LLM Harness 框架:用工程化手段把大模型幻觉踩在脚下
javascript·人工智能·后端
wei_shuo6 小时前
KES 云原生部署与弹性扩展:容器化、Kubernetes编排与自动伸缩
后端
一木之林6 小时前
Python.五.(一)--1. 并发编程、异步IO与多进程
后端
feng尘6 小时前
# 彻底搞懂 ReentrantLock 与 tryLock:从秒杀实战到 AQS 独占模式源码剖析
后端