I have a custom implementation of WebFilter to log outgoing responses and I've run into an issue with a wrong response status code. The status code is always 200 even though 500 is returned to the client if the exception is not handled by an ExceptionHandler. If it's handled by the handler, then the correct, non 200, status code is set. I use SpringBoot version 2.7.3. here is the code:

@Component
class GlobalLoggingFilter(private val log: Logger): WebFilter {
    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {

        return chain.filter(exchange).doOnError {
            val status = exchange.response.statusCode
            log.info(status?.toString() ?: "")
        }
    }
}

Comment From: bclozel

This is the expected behavior as error handling is applied last, after the WebFilter instances, if the error was not handled before that. You can see this in action here, the filters are applied at the HttpHandler level before the error handling infrastructure.

I don't think we should change this behavior as this error handling is the last chance to handle errors, even if they happen in during web filters processing. If we were to switch the order, WebFilter would not be able to see error messages anymore and the doOnError operator would never be called in your case.

At this stage, I think it's safe to assume that if an exception flows through there, it means that the response status is very likely to be changed to 500.

Comment From: mkubele

Oh ok, thank you @bclozel for the response! Where would you suggest to log the response with the correct response code? Just some examples where the code won't be changed to 500 - 400 Bad request or 405 Method Not Allowed

Comment From: bclozel

For these cases, you can look at the ResponseStatusException thrown and see the response status that will be applied eventually.