Spring-boot handle NoHandlerException in @ControllerAdvice
Asked Answered
P

1

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?

Pinball answered 16/9, 2019 at 14:12 Comment(6)
Could you try with @Order(Ordered.HIGHEST_PRECEDENCE) on the handler, let me know if this works.Ultraviolet
It didn't work in My controller advice, "ResponseEntityExceptionHandler" is extended. So I'm not using @ExceptionHandler except I have to override the method.Pinball
OK then put on its head these annotations: @Order(Ordered.HIGHEST_PRECEDENCE) @ControllerAdviceUltraviolet
you can refer github.com/s2agrahari/global-excpetion-handler-spring-boot for global exception handling for rest apis.Kelby
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...Pinball
Sure, I will do it.Ultraviolet
U
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

Ultraviolet answered 16/9, 2019 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.