Skip to content

Customize 404 Error Response for Rest API in Spring boot

By default, the Spring boot will return a whitelabel error page, but as a rest API server, it's better to return a JSON response to user like a normal API response.

For example, the GitHub rest API will return a JSON and when the resouce is not found.

Bash
curl https://api.github.com/hub
{
    "message": "Not Found",
    "documentation_url": "https://docs.github.com/rest"
}

To customize the 404 rest API response in Spring Boot, it's required,

  1. Enable throw-exception-if-no-handler-found in application.properties

    Properties
    spring.mvc.throw-exception-if-no-handler-found=true
    spring.web.resources.add-mappings=false
    

  2. Add the handler for NoHandlerFoundException

    Java
    @RestControllerAdvice
    public class NotFoundResolver {
        @ExceptionHandler(NoHandlerFoundException.class)
        @ResponseStatus(HttpStatus.NOT_FOUND)
        public ResponseDTO<String> handleNoHandlerFound(NoHandlerFoundException e, WebRequest request) {
            return ResponseDTO.fail(ErrorCode.USER_ERROR.getErrCode(), e.getLocalizedMessage());
            }
    }
    

Then it will return a JSON response when the resource is not found.

Bash
curl http://localhost:8080/api/404
{"errCode":203,"message":"No endpoint GET /api/404.","data":null}