使用 Spring boot + WebFlux 进行全局错误处理

问题描述 投票:0回答:4

在Spring boot Rest Controller中使用反应式编程时,如何全局处理异常?

我认为

@ControllerAdvice
不会起作用,因为我已经尝试过这个但不成功。

我的其他尝试目前是此选项,使用自定义属性:

@Component
public class OsvcErrorAttributes extends DefaultErrorAttributes {
    public OsvcErrorAttributes() {
        super(true);
    }

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        return assembleError(request);
    }

    private Map<String, Object> assembleError(ServerRequest request) {
        ServerException serverException = (ServerException)getError(request);

        Map<String, Object> errorAttributes = new HashMap<>();
        errorAttributes.put("message", serverException.getMessage());
        errorAttributes.put("errors", serverException.getErrorMap());
        return errorAttributes;
    }
}

和 WebExceptionHandler 像这样:

@Component
@Order(-2)
public class OsvcErrorHandler extends AbstractErrorWebExceptionHandler {
    public OsvcErrorHandler(ErrorAttributes errorAttributes,
                            ResourceProperties resourceProperties,
                            ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, applicationContext);

        // TODO: 25.06.2019 temporary workaround
        ServerCodecConfigurer serverCodecConfigurer = new DefaultServerCodecConfigurer();
        setMessageWriters(serverCodecConfigurer.getWriters());
        setMessageReaders(serverCodecConfigurer.getReaders());
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    private Mono<ServerResponse> renderErrorResponse(ServerRequest serverRequest) {

        final Map<String, Object> errorAttributes = getErrorAttributes(serverRequest, true);
        return ServerResponse.status(HttpStatus.BAD_REQUEST)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(errorAttributes));
    }
}

产生错误的代码:

@Data
@Service
public class ContactService {
    private final ContactRepository contactRepository;

    public Mono<Business> saveNewContact(Business business) {
        return contactRepository.save(business)
                .onErrorMap(throwable ->
                    ServerException.create(throwable.getMessage())
                        .persistError("ico", business.getIco(), "ICO is probably duplicate"));
    }
}

问题是这也行不通。我确实遵循了本教程,但我不知道我是否做错了什么。

spring-boot exception spring-webflux project-reactor
4个回答
2
投票

您只需在全局错误处理程序构造函数中使用 ServerCodecConfigurer 注入,如下所示。

public OsvcErrorHandler(GlobalErrorAttributes errorAttributes, ApplicationContext applicationContext, 
                ServerCodecConfigurer serverCodecConfigurer) {
   super(errorAttributes, new ResourceProperties(), applicationContext);
   super.setMessageWriters(serverCodecConfigurer.getWriters());
   super.setMessageReaders(serverCodecConfigurer.getReaders());
}

请在 git repository 中找到代码示例。


0
投票

尝试注入 ServerCodecConfigurer 而不是实例化它。执行此操作时,我还会注入

ViewResolversProvider
,尽管可能没有必要。

    public OsvcErrorHandler(
            final CustomErrorAttributes customAttributes,
            final ResourceProperties resourceProperties,
            final ObjectProvider<List<ViewResolver>> viewResolversProvider,
            final ServerCodecConfigurer serverCodecConfigurer,
            final ApplicationContext applicationContext
    ) {
        super(customAttributes, resourceProperties, applicationContext);

        this.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
        this.setMessageWriters(serverCodecConfigurer.getWriters());
        this.setMessageReaders(serverCodecConfigurer.getReaders());
    }

0
投票

您需要将

ErrorWebExceptionHandler
定义并实现为一个 bean,并设置值小于
@Order
-1
注解,因为这是 Spring 的默认值
DefaultErrorWebExceptionHandler

这是一个示例实现:

public class GlobalErrorHandler extends DefaultErrorWebExceptionHandler {
    public GlobalErrorHandler(
            final ErrorAttributes errorAttributes,
            final WebProperties.Resources resources,
            final ErrorProperties errorProperties,
            final ApplicationContext applicationContext) {
        super(errorAttributes, resources, errorProperties, applicationContext);
    }

    @Override
    public Mono<Void> handle(final ServerWebExchange exchange, final Throwable ex) {
        final ServerHttpResponse response = exchange.getResponse();
        if (ex instanceof IllegalStateException
                && StringUtils.equals("Session was invalidated", ex.getMessage())
                && response.getStatusCode().is3xxRedirection()) {
            final DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
            return response.writeWith(Mono.just(bufferFactory.wrap("Redirecting...".getBytes())));
        }
        return super.handle(exchange, ex);
    }
}

这是基于

org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration
类的示例配置:

@Configuration
public class ErrorWebFluxAutoConfiguration {

    private final ServerProperties serverProperties;

    public ErrorWebFluxAutoConfiguration(final ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Bean
    @Order(-2)
    public ErrorWebExceptionHandler errorWebExceptionHandler(
            final ErrorAttributes errorAttributes,
            final org.springframework.boot.autoconfigure.web.ResourceProperties resourceProperties,
            final WebProperties webProperties,
            final ObjectProvider<ViewResolver> viewResolvers,
            final ServerCodecConfigurer serverCodecConfigurer,
            final ApplicationContext applicationContext) {
        final GlobalErrorHandler exceptionHandler =
                new GlobalErrorHandler(
                        errorAttributes,
                        resourceProperties.hasBeenCustomized()
                                ? resourceProperties
                                : webProperties.getResources(),
                        serverProperties.getError(),
                        applicationContext);
        exceptionHandler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
        exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
    public DefaultErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }
}

感谢this文章指出我使用

ErrorWebExceptionHandler


0
投票

您可以使用

@ControllerAdvice
来处理自定义异常,但最好扩展
ResponseEntityExceptionHandler
类,该类用于处理控制器方法执行期间发生的异常。

该示例针对 Spring boot 和 WebFlux 进行了测试

3.1.5

@ControllerAdvice
@NonNullApi
public class LeaderboardExceptionHandler extends ResponseEntityExceptionHandler {

    private final Logger log = LoggerFactory.getLogger(LeaderboardExceptionHandler.class);

    @ExceptionHandler(ClientException.class)
    public Mono<ResponseEntity<CustomError>> handleClientException(ClientException clientException) {
        log.warn("Client exception with code [{}] and message [{}]",
                clientException.getCode(),
                clientException.getMessage());
        return Mono.just(ResponseEntity.status(HttpStatus.BAD_REQUEST.value())
                .body(new CustomError().code(clientException.getCode()).message(clientException.getMessage())));
    }

}

这是如何在逻辑中产生错误的

 private Mono<Game> validateInputDate(Game game) {
        // Some code here
        if (newGameMinDate < minGameStartTime) {
            return Mono.error(new ClientException(ErrorMessages.GAME_INVALID_INIT_DATE.getCode(),
                    String.format(ErrorMessages.GAME_INVALID_INIT_DATE.getMessage())));
        }
        return Mono.just(game);
    }

注意:您可以在建议中使用自定义对象,尽管

ResponseEntityExceptionHandler
中的大多数方法都使用
ProblemDetail
对象

© www.soinside.com 2019 - 2024. All rights reserved.