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,
-
Enable
throw-exception-if-no-handler-found
inapplication.properties
-
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.