Order ProblemDetailsExceptionHandler beans #36288
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
In this pull request I added an explicit zero order to the
ProblemDetailsExceptionHandler
beans for WebMVC and Webflux.Without the order, it means these beans automatically have the lowest precedence, and they will usually be executed last. This can be problematic when someone would like to create a “catch-all”
@ExceptionHandler
in a@ControllerAdvice
bean. Meaning an exception handler that should handle any exception that was not handled by any other exception handler with.Such an exception handler should have the absolute lowest precedence, and the
ProblemDetailsExceptionHandler
must have a higher precedence. However, because both now have the same precedence, it is not a guarantee that this will be the case. In my tests, my own catch-all exception handler would always start handling those exceptions that should be handled by theProblemDetailsExceptionHandler
.The workaround is to create custom beans that implement
ResponseEntityExceptionHandler
and give those an order that has a higher precedence then my catch-all exception handler. However, I don’t think this should be necessary.Because the
ResponseEntityExceptionHandler
has a defined list of exceptions it is going to handle, there should be no issue in it having a specific order by default. If it has the order0
then anyone can easily create an exception handler that has a higher or lower precedence.I created a test which shows the issue, and the current workaround:
https://github.com/mzeijen/spring-boot-problem-support/blob/main/src/test/java/com/example/demo/ResponseEntityExceptionHandlerOrderingTest.java
This test has nested test classes which show the difference in behavior for both WebMVC and Webflux, when the default
ResponseEntityExceptionHandler
are used or when the workaround is applied.In the pull request I added a test that verifies that the ordering takes effect.