Search code examples
springspring-bootspring-rest

How to wrap Path Not Found Exception in Spring Boot Rest using ExceptionHandler?


I am using Spring Boot and Spring Rest Example. In this example, I am passing custom header, if that value is valid, endpoint gets called successfully, if custom header value is not correct then I get below response, which I want to wrap into show it to the enduser using @ControllerAdvice ExceptionHandler.

Note: I went through Spring mvc - How to map all wrong request mapping to a single method, but here in my case I am taking decision based on CustomHeader.

{
    "timestamp": "2020-01-28T13:47:16.201+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/employee-data/employee-codes"
}

Controller

@Operation(summary = "Find Employee")
@ApiResponses(value = { @ApiResponse(code = 200, message = "SUCCESS"),
        @ApiResponse(code = 500, message = "Internal Server Error") })
@Parameter(in = ParameterIn.HEADER, description = "X-Accept-Version", name = "X-Accept-Version", 
        content = @Content(schema = @Schema(type = "string", defaultValue = "v1", 
        allowableValues = {HeaderConst.V1}, implementation = Country.class)))
@GetMapping(value = "/employees/employee-codes", headers = "X-Accept-Version=v1")
public ResponseEntity<Employees> findEmployees(
        @RequestParam(required = false) String employeeCd,
        @RequestParam(required = false) String firstName,
        @RequestParam(required = false) Integer lastName) {
    Employees response = employeeService.getEmployees(employeeCd, firstName, lastName);
    return new ResponseEntity<>(response, HttpStatus.OK);
}

I've implemented HttpMessageNotReadableException and HttpMediaTypeNotSupportedException and NoHandlerFoundException, but still not able to wrap this error.

Any suggestions?


Solution

  • I was able to find the solution for it.

    # Whether a "NoHandlerFoundException" should be thrown if no Handler was found to process a request.
    spring.mvc.throw-exception-if-no-handler-found=true
    spring.resources.add-mappings=false
    

    Error Handling Code:

    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers,
            HttpStatus status, WebRequest request) {
        // custom logic here
    
        return handleExceptionInternal(ex, error, getHeaders(), HttpStatus.BAD_REQUEST, request);
    }