Spring with Kotlin - REST API Error Handling

Handling exceptions gracefully, providing appropriate error messages is extremely important in developing REST APIs. It is obvious that Spring Boot already handles a lot of exceptions in ResponseEntityExceptionHandler. But when using Spring Framework from scratch, the error handling kind of becomes a necessity. In any case, customization is very much desirable on top of default responses provided by the Spring. In this blog post, I will explain how to create custom exceptions, throw meaningful error messages using an example. And yes, everything will be in Kotlin!

Let's say we create an API for getting Student information. We have GET mappings for retrieving all students or a single student based on student id.

Now, there are 4 steps in handling any error
  1. Create custom exception (Optional based on the scenario)
  2. Create a custom response template.
  3. Throw the exception in right place.
  4. Handle the exception and return an appropriate response.
Let's consider a scenario where we are expecting a resource not found and generic client-side errors. We will throw an exception and send a response if the requested student is not found. If there's a bad request made by a client, we will throw a generic exception for the sake of the simplicity of this blog post.

Following the 4 steps as I mentioned earlier:

Step 1: Create a custom exception

I have created a StudentNotFoundException which extends RuntimeException with the error message that we will pass from the code.

Step 2: Create a custom response template

We want to wrap our exception into an object and send an elegant response in JSON format. I have created a simple Kotlin class that contains fields - status code, message (from the exception), and a timestamp at which the exception is thrown.

Step 3: Throw the exception in the right place

In our StudentRestController class, I am throwing StudentNotFoundException I don't find id associated with the student in the list.

Step 4: Handle the exception and return an appropriate response

This is an important last step. We catch an exception here, create an error response object and send it back as a ResponseEntity. I have used a 404 Not Found status code corresponding to our StudentNotFoundException. For generic client errors, I am simply using 400 Bad Request with whatever error message that particular RuntineException provides. Note that StudentExceptionHandler can handle exceptions globally from multiple controllers by use of the annotation @ControllerAdvice. This AOP (Aspect Oriented Programming) approach allows pre-processing/post-processing requests in real-time.

Once you hit an exception, instead of default response, we can now see our own customized error response as a JSON. Just for the comparison -

Default Response -

Our customized error response -
Which one is easier to read? You tell me! 😀

Well, I hope you learned something new in this blog post. The entire code can be found on my GitHub. Thanks for reading and stay tuned for more!

PS - This is an excellent read to learn more about error handling.

Comments

Post a Comment

Popular Posts