I'm using Spring boot for hosting a REST API. Instead of having the standard error response I would like to always send a JSON response even if a browser is accessing the URL and as well a custom data structure.
I can do this with @ControllerAdvice and @ExceptionHandler for custom exceptions. But I can't find any good ways of doing this for standard and handled errors like 404 and 401.
Are there any good patterns of how to do this?
The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.
We went through the two most common reasons for receiving a 404 response from our Spring application. The first was using an incorrect URI while making the request. The second was mapping the DispatcherServlet to the wrong url-pattern in web. xml.
For those Spring Boot 2 users who don't wanna use @EnableWebMvc
application.properties
server.error.whitelabel.enabled=false spring.mvc.throw-exception-if-no-handler-found=true spring.resources.add-mappings=false
ControllerAdvice
@RestControllerAdvice public class ExceptionResolver { @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public HashMap<String, String> handleNoHandlerFound(NoHandlerFoundException e, WebRequest request) { HashMap<String, String> response = new HashMap<>(); response.put("status", "fail"); response.put("message", e.getLocalizedMessage()); return response; } }
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With