1

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

sineverba
  • 5,059
  • 7
  • 39
  • 84
  • You can catch the exception throws by Spring when no handler is found for a request. Details here: https://stackoverflow.com/questions/30329543/spring-boot-taking-control-of-404-not-found – Cyril G. Mar 21 '22 at 04:00
  • Do you find a solution @sineverba – Bilgehan May 13 '22 at 13:52

2 Answers2

0

Add following property in your application.properties:

spring.web.resources.add-mappings=false
Daniel Santana
  • 172
  • 1
  • 5
  • 10
0

For those who are still looking an answer:

  1. Define your custom ExceptionHandler that extends ResponseEntityExceptionHandler.

  2. Override the methode handleNoHandlerFoundException and return a ResponseEntity with your custom Error object.

  3. Add the following properties in your application.properties file:

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

    spring.web.resources.add-mappings=false