I am running web flux with Kotlin coroutines using spring boot 3.2 and the underlying version 6.1.1 of the spring framework.
I am using micrometer for tracing. With spring's coRouter
, I followed the example here: https://github.com/spring-projects/spring-framework/issues/27010 to set the context in my corouter, so all subsequent calls have access to the MdcContext
.
But if I define an onError
function, the context is not applied to that function. Is there a special way to do that, or do I have to send the context manually as a function parameter?
Example:
@Bean
fun demoRoutes() = coRouter {
"/rest".nest {
"v1".nest {
"/demo".nest {
context { observationRegistry.asContextElement() }
GET("", demoHandler::demoCall)
}
}
}
onError<RuntimeException> { throwable, serverRequest ->
errorHandler.handleError(throwable, serverRequest)
}
}
Another additional question:
Is there some way to make the context
apply for everything? It only applies if it is set in the last nest
function. If I define it to a parent or directly within coRouter
, it's not working:
@Bean
fun demoRoutes() = coRouter {
context { observationRegistry.asContextElement() }
"/rest".nest {
"v1".nest {
"/demo".nest {
GET("", demoHandler::demoCall)
}
}
}
onError<RuntimeException> { throwable, serverRequest ->
errorHandler.handleError(throwable, serverRequest)
}
}
If used like that, the context is lost in the call to demoHandler::demoCall
.
The behavior of error handling seems to be ok as far as I can tell, but there is indeed a surprising behavior when combining nested routers and
CoroutineContext
, this should be fixed by https://github.com/spring-projects/spring-framework/issues/31831.