1. Introduction
Happy-path REST is pretty well-understood, and Spring makes this easy to do in Java.
But what about when things go wrong?
In this tutorial, we’ll go over passing a Java exception as part of a JSON response using Spring.
For a broader look, check out our posts on error handling for REST with Spring and creating a Java global exception handler.
2. An Annotated Solution
We’re going to use three basic Spring MVC annotations to solve this:
- @ControllerAdvice to register the surrounding class as something each @Controller should be aware of
- @ExceptionHandler to tell Spring which of our methods should be invoked for a given exception
- @ResponseBody to tell Spring to render that method’s response as JSON
Together, these create a Spring bean that handles any exceptions we configure it for. Here are more details about using @ControllerAdvice and @ExceptionHandler in conjunction.
3. Example
Firstly, let’s create an arbitrary custom exception to return to the client.
public class CustomException extends RuntimeException { // constructors }
Secondly, let’s define a class to handle the exception and pass it to the client as JSON.
@ControllerAdvice @ResponseBody public class ErrorHandler { @ExceptionHandler(CustomException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public CustomException handleCustomException(CustomException ce) { return ce; } }
Note that we added the @ResponseStatus annotation. This will specify the status code to send to the client, in our case an Internal Server Error. Also, the @ResponseBody will ensure that the object is sent back to the client serialized in JSON. Finally, below is a dummy controller that shows an example of how the exception can be thrown.
@Controller public class MainController { @GetMapping("/") public void index() throws CustomException { throw new CustomException(); } }
4. Conclusion
In this post, we showed how to handle exceptions in Spring. Moreover, we showed how to send them back to the client serialized in JSON.
The full implementation of this article can be found over on Github. This is a Maven-based project so it should be easy to import and run as it is.