Skip to content

Context not propagated in exception handler in Webflux #35636

@PheelTi

Description

@PheelTi

Hi,

I think it is an issue... but you may qualify this as an enhancement.

in short : a context set in a high level WebFilter is not propagated in the exception handler

I have sample project here : https://github.com/PheelTi/spring-webflux-context

  • Weblux / Kotlin / Micrometer context propagation
  • a custom ErrorWebExceptionHandler which adds a log and delegate the error handling to a DefaultErrorWebExceptionHandler
  • I have a custom context MyContext managed in a ThreadLocal and I want it to be propagated, to do so, I have implemented :
    • a CoWebFilter which propagates the Kotlin context with a custom ThreadContextElement
    • I used the ContextRegistry.getInstance().registerThreadLocalAccessor(...) to register the access to MyContext
    • I activated Hooks.enableAutomaticContextPropagation()
  • the value of MyContext is created in a high level businessWebFilter, and set in its ThreadLocal, and in the Reactor Context, and I print its value in several places :
    • in the business filter juste after initialisation, and around its cleaning
    • in the controller
    • in the exception handler.

Here are the results :

[INFO]  Context from 'starting request processing' : is present with value 'request 6c8d08dd-6238-48c1-b295-5c134f1c6b7a'
[INFO]  Context from 'controller processing' :  is present with value 'request 6c8d08dd-6238-48c1-b295-5c134f1c6b7a'
[INFO]  Context from 'exception handler' : is not present
[ERROR]  500 Server Error for HTTP GET "/test"

java.lang.RuntimeException: test exception
...

[INFO]  Context from 'finishing request processing' : is present with value 'request 6c8d08dd-6238-48c1-b295-5c134f1c6b7a'
[INFO]  Context from 'cleaned request processing' : is not present

I would expect to have MyContext also present in the exception handler...

I found those workarounds though :

  • annotate the exception handler class with @ControllerAdvice and the handle method with @ExceptionHandler(Throwable::class)
  • set my context in a higher level place like HttpHandlerDecoratorFactory

Thanks

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions