'Override the handleNoHandlerFoundException

I want override the Spring Boot default result when calling a not-existing route:

{
    "timestamp": "2022-03-20T17:01:07.453+00:00",
    "status": 404,
    "error": "Not Found",
    "path": "/api/v1/not-found"
}

I have a ControllerAdvisor

@ControllerAdvice
public class ControllerAdvisor extends ResponseEntityExceptionHandler {
  @Override
  protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
      return ResponseEntity.badRequest().body(new ErrorResponse("path not found"));
  }
}

that it works for others custom exception.

I have also added (or removed) this property on application.properties but nothing change:

spring.mvc.throw-exception-if-no-handler-found=true

Spring boot starter parent is v. 2.6.4



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source