Search code examples
javaspring-bootrestexceptionhandler

How to modify default spring boot not found url exception with custom message


I'm trying to modify the default error message and status code for all non supported rest end points.

How to do it ?

My Customer error message

public class ApiErrorResponse {

    private int code;
    private String message;

    public ApiErrorResponse(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public int getCode() {
        return code;
    }
}

Custom error handling logic:

@ControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler({NoHandlerFoundException.class})
    public ResponseEntity<ApiErrorResponse> handleNoHandlerFoundException(
            NoHandlerFoundException ex, HttpServletRequest httpServletRequest) {
        ApiErrorResponse apiErrorResponse = new ApiErrorResponse(404, "Resource not found");
        return ResponseEntity.status(HttpStatus.NOT_FOUND).contentType(MediaType.APPLICATION_JSON).body(apiErrorResponse);
    }
}

and now tried like curl --location 'localhost:8080/some/invalid/url' But it gives default 404 status code and error message. not custom message . What I'm missing here ?


Solution

  • Inorder to identify which default error method we need to override, ResponseEntityExceptionHandler.java base class and identify the method to override. Here NoHandlerFoundExceptionand handleNoHandlerFoundException() need to be overridden. above code properly overridden. please add @EnableWebMvc in the application.java or @configuration class to identify override methods.