当前位置: 代码网 > it编程>编程语言>Java > Spring Boot @RestControllerAdvice全局异常处理最佳实践

Spring Boot @RestControllerAdvice全局异常处理最佳实践

2025年07月02日 Java 我要评论
前言在开发spring boot应用时,优雅地处理异常是保证系统健壮性和用户体验的关键。本文将详细介绍如何使用@restcontrolleradvice实现全局异常处理,并分享实际开发中的最佳实践。一

前言

在开发spring boot应用时,优雅地处理异常是保证系统健壮性和用户体验的关键。本文将详细介绍如何使用@restcontrolleradvice实现全局异常处理,并分享实际开发中的最佳实践。

一、为什么要使用全局异常处理?

  1. 代码复用:避免在每个controller中重复编写try-catch

  2. 统一响应格式:标准化错误返回结构

  3. 异常分类处理:针对不同类型异常定制处理逻辑

  4. 减少样板代码:让业务逻辑更专注于核心流程

二、核心注解解析

1. @restcontrolleradvice

@restcontrolleradvice@controlleradvice@responsebody的组合注解,主要功能:

@target(elementtype.type)
@retention(retentionpolicy.runtime)
@documented
@controlleradvice
@responsebody
public @interface restcontrolleradvice {
    // 可指定包路径或控制器类
    @aliasfor(annotation = controlleradvice.class)
    string[] value() default {};
}

2. @exceptionhandler

用于标注处理特定异常的方法:

@target(elementtype.method)
@retention(retentionpolicy.runtime)
@documented
public @interface exceptionhandler {
    // 指定要处理的异常类数组
    class<? extends throwable>[] value() default {};
}

三、实战代码实现

以下是完整全局异常处理器实现:

他会对于exceptionhandler指定的异常进行处理,底层是通过aop的技术实现的。

import com.sheep.shrine.result.jsonresult;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.restcontrolleradvice;
/**
 * 全局异常处理器
 * @restcontrolleradvice = @controlleradvice + @responsebody
 */
@restcontrolleradvice
public class globalexceptionhandler {
    /**
     * 处理自定义业务异常
     */
    @exceptionhandler(globleexception.class)
    public jsonresult handlebusinessexception(globleexception e) {
        e.printstacktrace();
        return jsonresult.error(e.getmessage());
    }
    /**
     * 处理所有未捕获异常
     */
    @exceptionhandler(exception.class)
    public jsonresult handlesystemexception(exception e) {
        e.printstacktrace();
        return jsonresult.error("系统异常,正在殴打程序员...", "50000");
    }
}

四、进阶使用技巧

1. 异常分类处理

// 处理数据校验异常
@exceptionhandler(methodargumentnotvalidexception.class)
public jsonresult handlevalidexception(methodargumentnotvalidexception e) {
    string message = e.getbindingresult().getallerrors()
            .stream()
            .map(defaultmessagesourceresolvable::getdefaultmessage)
            .collect(collectors.joining("; "));
    return jsonresult.error(message);
}
// 处理数据库异常
@exceptionhandler(dataaccessexception.class)
public jsonresult handledataaccessexception(dataaccessexception e) {
    log.error("数据库操作异常", e);
    return jsonresult.error("数据库服务异常");
}

2. 响应状态码控制

@exceptionhandler(unauthorizedexception.class)
@responsestatus(httpstatus.forbidden)
public jsonresult handleunauthorizedexception(unauthorizedexception e) {
    return jsonresult.error("无权限访问", "403");
}

3. 日志记录优化

@slf4j
@restcontrolleradvice
public class globalexceptionhandler {
    @exceptionhandler(exception.class)
    public jsonresult handleexception(exception e) {
        log.error("系统异常: {}", e.getmessage(), e);
        return jsonresult.error("系统繁忙");
    }
}

五、最佳实践建议

  1. 异常分类细化:不要只用一个exception.class处理所有异常

  2. 敏感信息过滤:生产环境不要返回堆栈信息

  3. 错误码规范:制定统一的错误码体系

  4. 日志完善:关键异常必须记录完整上下文

  5. 性能考虑:异常处理逻辑应尽量轻量

六、常见问题解答

q1:全局异常处理器不生效怎么办?

  • 检查是否在spring扫描路径下

  • 确认没有其他异常处理器覆盖

  • 检查是否有filter提前处理了异常

q2:如何测试全局异常处理器?

@springboottest
class globalexceptionhandlertest {
    @autowired
    private webapplicationcontext context;
    private mockmvc mockmvc;
    @beforeeach
    void setup() {
        mockmvc = mockmvcbuilders.webappcontextsetup(context).build();
    }
    @test
    void testbusinessexception() throws exception {
        mockmvc.perform(get("/api/test-exception"))
               .andexpect(status().isok())
               .andexpect(jsonpath("$.code").value("50000"));
    }
}

q3:如何与feignclient集成?

@configuration
public class feignconfig {
    @bean
    public errordecoder errordecoder() {
        return (methodkey, response) -> {
            // 将feign异常转换为自定义异常
            return new businessexception("远程服务调用失败");
        };
    }
}

七、总结

通过@restcontrolleradvice实现全局异常处理可以:

  1. 提高代码可维护性

  2. 增强系统健壮性

  3. 改善用户体验

  4. 便于监控报警

到此这篇关于spring boot @restcontrolleradvice全局异常处理最佳实践的文章就介绍到这了,更多相关spring boot @restcontrolleradvice全局异常内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com