Spring webflux error handler: How to get the reactor context of the request in the error handler?

Arnaud Villevieille

Spring boot 2.1.5 Project Reactor 3.2.9

In my webflux project, I extensively use the reactor contexts in order to pass around some values.

My purpose here is to be able to get the context inside of the Exception handler.

A simple example:

@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends
    AbstractErrorWebExceptionHandler {

    public GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext, ServerCodecConfigurer configurer) {
        super(errorAttributes, resourceProperties, applicationContext);
        this.setMessageWriters(configurer.getWriters());
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(
      ErrorAttributes errorAttributes) {
        return RouterFunctions
            .route(RequestPredicates.all(), request -> {
                Throwable error = errorAttributes.getError(request);

                return ServerResponse.status(500).syncBody(error.getMessage()).doOnEach(serverResponseSignal -> {
                    //Here the context is empty because i guess i created a new flux
                    System.out.println("What is in my context ? " + serverResponseSignal.getContext());
                    System.out.println("What is my exception ? " + error);
                });
            });
    }

}

I am not sure how to achieve that goal in a clean way with reactor. Anyone an idea ?

Arnaud Villevieille

I found a trick to be able to achieve that. It does not sound clean but it seems to work.

In a filter, I keep the subscribed context into a request attribute:

@Component
public class MdcWebFilter implements WebFilter {

    @NotNull
    @Override
    public Mono<Void> filter(@NotNull ServerWebExchange serverWebExchange,
                             WebFilterChain webFilterChain) {

        Mono<Void> filter = webFilterChain.filter(serverWebExchange);
        return filter
            .subscriberContext((context) -> {
                //This code is executed before the query

                Context contextTmp = context.put("whatever", "whichever");

                //I save the context in an attribute attribute
                serverWebExchange.getAttributes().put("context", contextTmp);

                return contextTmp;
            });
    }
}

Then after that it is possible to get it from the reactive error handler:

@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends
    AbstractErrorWebExceptionHandler {

    public GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext, ServerCodecConfigurer configurer) {
        super(errorAttributes, resourceProperties, applicationContext);
        this.setMessageWriters(configurer.getWriters());
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(
      ErrorAttributes errorAttributes) {
        return RouterFunctions
            .route(RequestPredicates.all(), request -> {
                Throwable error = errorAttributes.getError(request);

                //The context will be visible in the whole error handling flow
                return ServerResponse.status(500).syncBody(error.getMessage())
                   .subscriberContext((Context) request.attribute("context").orElse(Context.empty())));
            });
    }

}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

PHP error handler - how to get error name

分類Dev

How to get the context of the current request in spring-webflux

分類Dev

How to redirect correctly in a global error handler

分類Dev

Handler in android giving error

分類Dev

Completion Handler Error in Swift

分類Dev

Spring security error with access-denied-handler tag

分類Dev

Spring WebFlux/ Reactor core

分類Dev

Vba 'on error' handler does not appear to work

分類Dev

Error handler working even without errors

分類Dev

Typescript React <Select> onChange handler type error

分類Dev

Catcher Error Handler in Main() and instantiated variables

分類Dev

Spring Kafka Error Handler無限ループを回避する方法

分類Dev

How to define a default handler in Spring Boot 2

分類Dev

NodeJS http request handler

分類Dev

how to let @ExceptionHandlers handle specific exceptions before defaulting to an Exception handler for any Runtime error?

分類Dev

How does Node.js know if the first parameter of a callback is an error handler?

分類Dev

How do I prevent a checkbox from looking selected if click handler causes error

分類Dev

General error handler for Angular2 application using Material Design

分類Dev

STM32F4 Error Handler and allowed operations

分類Dev

Symfony Tactician-bundle Typehints = Missing handler method error

分類Dev

Laravel error Declaration of App\Exceptions\Handler::report(Throwable $exception)

分類Dev

addActionListener doesn't work I got an error on the .Handler

分類Dev

ASIO handler arguments and boost::bind, compile time error

分類Dev

How to add error response format in Swagger for a Spring-boot project based on webflux

分類Dev

how function handler function handler work in JQuery

分類Dev

How to call this completion handler?

分類Dev

How to access execution context from a Spring Batch Step? Error: No context holder available for job scope

分類Dev

How to get jQuery to trigger a native custom event handler

分類Dev

how to get Python logging messages to appear for modules using custom handler

Related 関連記事

  1. 1

    PHP error handler - how to get error name

  2. 2

    How to get the context of the current request in spring-webflux

  3. 3

    How to redirect correctly in a global error handler

  4. 4

    Handler in android giving error

  5. 5

    Completion Handler Error in Swift

  6. 6

    Spring security error with access-denied-handler tag

  7. 7

    Spring WebFlux/ Reactor core

  8. 8

    Vba 'on error' handler does not appear to work

  9. 9

    Error handler working even without errors

  10. 10

    Typescript React <Select> onChange handler type error

  11. 11

    Catcher Error Handler in Main() and instantiated variables

  12. 12

    Spring Kafka Error Handler無限ループを回避する方法

  13. 13

    How to define a default handler in Spring Boot 2

  14. 14

    NodeJS http request handler

  15. 15

    how to let @ExceptionHandlers handle specific exceptions before defaulting to an Exception handler for any Runtime error?

  16. 16

    How does Node.js know if the first parameter of a callback is an error handler?

  17. 17

    How do I prevent a checkbox from looking selected if click handler causes error

  18. 18

    General error handler for Angular2 application using Material Design

  19. 19

    STM32F4 Error Handler and allowed operations

  20. 20

    Symfony Tactician-bundle Typehints = Missing handler method error

  21. 21

    Laravel error Declaration of App\Exceptions\Handler::report(Throwable $exception)

  22. 22

    addActionListener doesn't work I got an error on the .Handler

  23. 23

    ASIO handler arguments and boost::bind, compile time error

  24. 24

    How to add error response format in Swagger for a Spring-boot project based on webflux

  25. 25

    how function handler function handler work in JQuery

  26. 26

    How to call this completion handler?

  27. 27

    How to access execution context from a Spring Batch Step? Error: No context holder available for job scope

  28. 28

    How to get jQuery to trigger a native custom event handler

  29. 29

    how to get Python logging messages to appear for modules using custom handler

ホットタグ

アーカイブ