springboot自定义异常拦截失败

springboot自定义异常拦截失败,使用分布式,从gateway转发至指定模块,单独写了一个工具类,其中异常也写在内,通过maven形式将工具类放入至模块,但是未拦截成功,麻烦帮忙看下,谢谢。代码如下

工具类代码

public class CustomException extends RuntimeException{
    private static final long serialVersionUID = 440796089575624843L;

    public CustomException(String message) {
        super(message);
    }
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler
    @ResponseBody
    public Result defaultErrorHandler(Exception e, HttpServletResponse response) {

        if (e instanceof CustomException) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return Result.fail(StatusCode.Error.toString(),e.getMessage());
        } else if (e instanceof ValidationException) {
            response.setStatus(HttpStatus.NOT_IMPLEMENTED.value());
            return Result.fail(StatusCode.Validation_Error.toString(),e.getMessage());
        } else {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return Result.fail(StatusCode.Other_Error.toString(),e.getMessage());
        }
    }

后面就是抛出异常了,控制台输出为

img

通过apifox调用后未获取异常消息成功,且也不是自己封装的响应

img

下面这个图是响应成功的实例

img

后面的话我把这个globalExceptionHandler 丢到业务模块里面就生效了,自定义异常就生效了,这总不能每个业务模块都定义globalExceptionHandler吧,那不得爽死

把GlobalExceptionHandler 在gateway启动类上面扫描进去

定义了异常处理类还需要去加载它,我是这样写的

@Configuration
public class SpringWebAutoConfiguration implements WebMvcConfigurer {

    @Bean
    @ConditionalOnMissingBean
    public GlobalExceptionHandler globalExceptionHandler() {
        return new GlobalExceptionHandler();
    }
}

直接将GlobalExceptionHandler类放到公共模块,再使用注解@Component标注,通常来说每个模块的@SpringBootApplication注解都能将其加载到容器,从而拦截生效。