spring-framework
spring-framework copied to clipboard
Allow `@ControllerAdvice` in WebFlux to handle exceptions before a handler is selected
Affects: 5.1.7.RELEASE
When I tried to handle the http 405
error with @ExceptionHandler
I found that I couldn't catch the MethodNotAllowedException
exception in webflux
, which can be done in the web mvc
by catching the HttpRequestMethodNotSupportedException
exception. Is this a bug or is it not supported or is there another way to do it?
I found another way to do this, using WebExceptionHandler
.
@Bean
@ConditionalOnMissingBean(name = "globalWebExceptionHandler")
@Order(Ordered.HIGHEST_PRECEDENCE + 1000)
public WebExceptionHandler globalWebExceptionHandler() {
return ReactiveExceptionUtils::handleException;
}
I delegated the exception to the @ExceptionHandler
bean.
But I think this is not very good. Is there any better advice?
An @ExceptionHandler
only handles errors from the controller, while the 405 happens earlier as part of request mapping. The WebExceptionHandler
mechanism is global enough to handle all errors so that's the right place to do it.
As you are in a Spring Boot application there are options to customize error handling at that level.
I'm having the same issue I was expecting the spring framework to be agnostic of the server and I could centralize the exception handling from my ControllerAdvice as @wangxing-git mentioned we can do that when running the application with tomcat. Is there a way to bring this convenience to the framework?
The handling of exceptions before a controller method is selected is a relatively recent Spring MVC feature, added in 5.3 with #22619. We could align the two and provide an equivalent feature in WebFlux.
Given the new addition of ResponseEntityExceptionHandler as a part of https://github.com/spring-projects/spring-framework/issues/27052 I would expect there this to work. As of the moment I can't get a subclass (annotated with ContollerAdvice) to handle exceptions like method not supported even though the code implies this should work. Maybe be missing a configuration item though...
Hi, this is still happening with a 404 as it comes back with the original response:
{
"timestamp": "2022-11-10T09:40:11.551+00:00",
"path": "/",
"status": 404,
"error": "Not Found",
"message": null,
"requestId": "3da6254c-1"
}
I would have thought this would have been fixed with 307247b is the intended behaviour?
Odd, we have a test for that.
Ah I see, that is not what is being displayed. Do you want a zip project file with the issue?
Sure, or a github repo.