解决SpringBoot项目中@RestControllerAdvice全局异常失效问题

1、问题

使用@RestControllerAdvice添加了全局异常,但没有生效


/**
 * 全局异常处理
 * @author Eric
 * @date 2022-10-08 10:00:22
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(WxRedpackController.class);

    /**
     * 用来拦截valid的校验
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object handleVaildException(MethodArgumentNotValidException e) {
        logger.info("数据校验出现问题:{},异常类型:{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
            Map<String, String> errorMap = new HashMap<>();
            result.getFieldErrors().forEach((item) -> {
                //获取到的错误提示
                String message = item.getDefaultMessage();
                //获取到的错误属性名称
                String field = item.getField();
                errorMap.put(field, message);
            });
            return ResponseUtil.fail(DATA_ERROR.code(),errorMap);
        }
        return ResponseUtil.fail();
    }


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Object notFount(RuntimeException e) {
        logger.info("运行时异常:", e);
        return ResponseUtil.fail(DATA_ERROR.code(),e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        logger.info(e.getMessage(), e);
        return ResponseUtil.fail(DATA_ERROR.code(),"服务器网络拥堵,请稍后再试");
    }

}

2、解决

方式1:@ExceptionHandler 所在类没有被Spring管理

因为 @SpringbootApplication默认扫描本包和子包,为了防止 全局异常类未被扫描到,建议在启动类上加上包扫描

在这里插入图片描述

方式2:AOP process() 没有异常抛出,自然不会被拦截掉。检查项目中的切面编程,查看是否在某个切面将异常try-catch,然后没有扔出来。

方式3:在@RestControllerAdvice @ConrollerAdivce 所在的类使用@Order(999999),注意这里不要引用错误的包了了,org.springframework.core.annotation.Order

在这里插入图片描述
参考1:参考1
参考2:参考2

### RestControllerAdvice 失效解决方案 #### 启动类配置不当 如果 `@RestControllerAdvice` 所在的包不在应用程序的主要启动类所在的包及其子包内,则该注解不会生效。为了确保全局异常处理器能够被正确加载,可以在启动类上显式指定组件扫描路径[^3]。 ```java @SpringBootApplication(scanBasePackages = {"com.example.global", "com.example.controller"}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` #### 安全框架冲突 当集成像 Spring Security 这样的安全框架时,可能会遇到全局异常处理机制失效的情况。这是因为某些过滤器会在请求到达控制器之前拦截并处理异常,从而阻止了自定义的全局异常处理器发挥作用。一种常见的解决办法是在 Spring Security 的过滤器链前添加自己的异常捕获逻辑[^5]。 ```java @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.addFilterBefore(new CustomExceptionHandlingFilter(), ChannelProcessingFilter.class); ... } private static final class CustomExceptionHandlingFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { filterChain.doFilter(request, response); } catch (Throwable t) { // 自定义异常响应处理... } } } } ``` #### 返回类型不匹配 另一个可能导致 `@RestControllerAdvice` 无法正常工作的原因在于返回类型的差异。对于 RESTful API 来说,应该使用 `@RestControllerAdvice` 而不是普通的 `@ControllerAdvice`;而对于视图渲染的应用场景则相反。此外,在编写具体的 `@ExceptionHandler` 方法时也要注意其返回值应与预期一致,比如 JSON 数据或 HTTP 响应状态码等[^1]。 ```java @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleResourceNotFound( ResourceNotFoundException ex){ ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage()); return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND); } // 更多异常处理器... } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eric-x

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值