I have this code snippet here:
@Component
class ResponseHeadersWebFilter : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
exchange.response.beforeCommit {
Mono.subscriberContext().doOnNext { context ->
context.get<Map<String, String>>(CONTEXT_MAP).let {
exchange.response.headers.apply {
add(HEADER_REQUEST_ID, it[METADATA_REQUEST_ID])
add(HEADER_USER, it[METADATA_USER])
}
}
}.then()
}
val contextMap = exchange.request.headers.toSingleValueMap().let {
mapOf(
METADATA_REQUEST_ID to it[HEADER_REQUEST_ID],
METADATA_USER to it[HEADER_USER]
)
}
return chain.filter(exchange).subscriberContext(Context.of(CONTEXT_MAP, contextMap))
}
}
The idea is to put request headers into context, and then add them from context to the response (based on this article)
It works if the request is processed successfully
However, if there is an exception then the context becomes empty
I checked from within the relevant @ExceptionHandler method (using coroutineContext[ReactorContext] in a suspending function) and it sees the headers in the context. But when it moves on to WebFilter's beforeCommit, somewhere along the way it loses the context. Moreover, @ExceptionHandler and WebFilter are in the same thread and the same coroutine
Any idea where to look? I'd appreciate any help!