spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.21k stars 37.97k forks source link

Throw exception if no handler found in Webflux #29568

Closed alxxyz closed 1 year ago

alxxyz commented 1 year ago

How to throw exception if no handler found in Webflux?

jaDEVirek commented 1 year ago

Hi @alxxyz

By default, the DispatcherServlet does not throw a NoHandlerFoundException. You need to enable that:

Check if you have right configuration in your application.properties. spring.mvc.throw-exception-if-no-handler-found=true

Besides, if you are using @EnableWebMvc then it is likely that your changes made, for example, in properties files will be overwritten. https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-servlet-config

alxxyz commented 1 year ago

I am using Webflux instead of WebMvc, does it work also for Webflux?

rstoyanchev commented 1 year ago

@alxxyz that should be the case out of the box in WebFlux, in DispatcherHandler.

alxxyz commented 1 year ago

@rstoyanchev can you please advise how I can catch it and override the response? As I can not catch it in the @ControllerAdvice

rstoyanchev commented 1 year ago

@alxxyz, catching early exceptions from before a handler is chosen was added recently for 6.0 with #22991, so it's not supported in 5.3.x. Are you trying to add a body to the error response or something else?

alxxyz commented 1 year ago

Yes, we have an API contract and I need to send a custom body

rstoyanchev commented 1 year ago

I see, so that's supported from 6.0 onwards. In 5.3.x, you can use a WebExceptionHandler as a workaround, or Boot's error handling.

alxxyz commented 1 year ago

Thank you @rstoyanchev