This recipe presents a technique for handling exception globally in a web application.
There are different ways to handle exceptions in Spring MVC. We can choose to define controller-specific @ExceptionHandler
or we can choose to register @ExceptionHandler
globally in the @ControllerAdvice
classes.
We developed the second option in our REST API, even if our CloudstreetApiWCI
super-class could have shared @ExceptionHandler
among its controllers.
Now we will see how to automatically map custom and generic exception types to HTTP status codes, and how to wrap the right error messages in a generic response object that can be used by any client.
We need a wrapper object to be sent back to the client when an error occurs:
public class ErrorInfo { public final String error; public int status; public final String date; private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); public ErrorInfo...