Kandy
Kandy

Reputation: 1087

Spring-boot handle NoHandlerException in @ControllerAdvice

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?

Upvotes: 2

Views: 2030

Answers (1)

Jonathan JOhx
Jonathan JOhx

Reputation: 5968

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

Upvotes: 3

Related Questions