RESTful Error Handling with Spring

This post will illustrate a way in which exception handling can be implemented for RESTful web services in Spring in such a manner that the exception handling concerns are separated from the application logic.

Taking advantage of the @ControllerAdvice annotation we are able to create a global helper class for all controllers. By adding methods that we annotate with both @ExceptionHandler and @ResponseStatus we can specify which type of exception gets mapped to which HTTP response status. E.g., our custom NotFoundException can be mapped to a HTTP response of 404 Not Found, or all exceptions that are not caught elsewhere will result in HTTP status 500 Internal Server Error by catching java.lang.Exception, or an IllegalArgumentException can result in 400 Bad Request, or… well, I’m sure you got the general idea.

If required, you can also send back some more detail to the client by adding @ResponseBody into the mix.