2

I want to handle NoHandlerException in Springboot app and return a custom error message. I added following to my application.properties and tried to override the error message.

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

Error doesn't hit the @ControllerAdvice... It is handled in defaulthandlerexceptionresolver . Any ideas?

Kandy
  • 1,067
  • 12
  • 29
  • Could you try with `@Order(Ordered.HIGHEST_PRECEDENCE)` on the handler, let me know if this works. – Jonathan JOhx Sep 16 '19 at 14:29
  • It didn't work in My controller advice, "ResponseEntityExceptionHandler" is extended. So I'm not using @ExceptionHandler except I have to override the method. – Kandy Sep 16 '19 at 15:17
  • 1
    OK then put on its head these annotations: `@Order(Ordered.HIGHEST_PRECEDENCE) @ControllerAdvice` – Jonathan JOhx Sep 16 '19 at 15:24
  • you can refer https://github.com/s2agrahari/global-excpetion-handler-spring-boot for global exception handling for rest apis. – Suraj Sep 16 '19 at 15:25
  • Thanx, @JonathanJohx, it worked. Can you please add it as an answer ? So this would be useful for others as well. How ever, Thank you very much saved a lot of my time... – Kandy Sep 16 '19 at 16:21
  • Sure, I will do it. – Jonathan JOhx Sep 16 '19 at 16:29

1 Answers1

3

Putting @Order(Ordered.HIGHEST_PRECEDENCE)and @ControllerAdvice on the exceptions handler head, it means:

@ControllerAdvice

Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes.

@Order

Defines the sort order for an annotated component. If we put as Ordered.HIGHEST_PRECEDENCE which is useful constant for the highest precedence value.

The code should be shown like this:

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ExceptionsHandler extends ResponseEntityExceptionHandler {
    .....
}

REFERENCES:

@ControllerAdvice annotation documentation

@Order annotation documentation

Jonathan JOhx
  • 5,784
  • 2
  • 17
  • 33