2
votes

I'm having a problem trying to return a "ResponseEntity" in one of my methods which is located in a custom exception handler (annotated with @ExceptionHandler and @ControllerAdvice), I'm calling this method from a "doOnError" (rxjava), but my problem is that when I do this not only my method is called, also another @ExceptionHandler in a @ControllerAdvice annotated class is called, but this class is not in my project, is in one of my dependencies.. so, to clarify my problem:

I'm trying to handle every exceptions in my project returning a ResponseEntity, but when I do this on my @ExceptionHandler inside my @ControllerAdvice, another one located in my dependencies is called after my custom one, so the response entity that I've build, is never returned, It just return the created by the dependency @ExceptionHandler.

My question is, there is a way to avoid the call to the dependency exception handler?

Notes:

  • the @ExceptionHandler is being used for the method inside the exception handler class, this last one is annotated with @ControllerAdvice.
  • I've tried with the Order and Priority annotations but they didn't work for me.
2

2 Answers

1
votes

You can prevent classes from being loaded using @ComponentScan from Spring (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html#excludeFilters).

You can either create a custom exclusion filter for that specific ExceptionHandler class, define the packages you want to exclude (might not be feasible depending on the package where the handler is defined) or even define specific classes to exclude.

0
votes

I solved my problem. I tried with the @ComponentScansolution proposed by João and it didn't work for me because the exception handler located in my dependencies is not annotated as a component.. so I started to research again and I figured it out that when I add another parameter to the "handleException" method in my exception handler (which is annotated as @ExceptionHandler) it doesn't works, because I deleted the second parameter (I had only the "throwable") and it started to work! So in resume, I added the ..

@Order(Ordered.HIGHEST_PRECEDENCE)

..annotation to my exception handler class and put only one parameter (the exception) in the @ExceptionHandler annotated method, which will retrieve the "ResponseEntity" that I needed.