Error handling
So far in our application, we haven't defined any specific error handler to catch the error and convey it to the right format. Usually when we deal with an unexpected situation in REST APIs, it will automatically throw an HTTP error such as 404
. Errors such as 404
will show explicitly in the browser. This is fine normally; however, we might need a JSON format result regardless of whether things go right or wrong.
Converting the error into JSON format would be a nice idea in such cases. By providing the JSON format, we can keep our application clean and standardized.
Here, we will discuss how to manage errors and display them in JSON format when things go wrong. Let's create a common error handler class to manage all of our errors:
public class ErrorHandler { @ExceptionHandler(Exception.class) public @ResponseBody <T> T handleException(Exception ex) { Map<String, Object> errorMap = new LinkedHashMap<>(); if(ex instanceof org.springframework.web...