Global error handling using Spring boot + WebFlux

Viewed 8153

How can we handle exceptions globally when using reactive programming in Spring boot rest controller?

I would assume that @ControllerAdvice will not work because I have tried this and it was unsuccessful.

My other try is currently this option, using custom attributes:

@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;
    }
}

and WebExceptionHandler like this:

@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));
    }
}

Code that generates an error:

@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"));
    }
}

Problem is that this does not work either. I did follow this tutorial and I cannot see if I am wrong with something or not.

3 Answers

You just use ServerCodecConfigurer injection in you global error handler constructor like this.

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

Please find the code example in the git repository.

Try injecting the ServerCodecConfigurer instead of instantiating it. I also inject a ViewResolversProvider when doing this, although it might not be necessary.

    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());
    }

You need to define and implement ErrorWebExceptionHandler as a bean and set an @Order annotation with value less than -1, because that is the default of the Spring DefaultErrorWebExceptionHandler

Here is a sample implementation:

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);
    }
}

And here is a sample configuration based on org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration class:

@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();
    }
}

Thanks to this article which points me to use ErrorWebExceptionHandler.

Related