Exception Handling in Spring Boot

Exception Handling in Spring Boot

Handle the exceptions in a more strategic way!!

ยท

4 min read

What you will learn from this blog?

  1. What is Exception Handling

  2. Default Exception Handling

  3. Custom Exception Handling

When we develop a Spring Boot application, As a developer we are responsible for handling the unwanted behaviour of our application. This unwanted behaviour is termed an Exception.

What is Exception Handling

Generally, When an exception occurs in the application, The API consumers will not understand the message received as a JSON response. It is our responsibility to handle the exception and customize the response. This process is termed Exception Handling.

There are several ways to handle the exceptions in Spring Boot Application. Let us develop a Spring Boot Application and implement the Exception Handling.

This Application will have a Library Controller using which we can add and get books with the help of REST API. We are using H2 which is an in-memory database along with Spring JPA.

Default Exception Handling

By default, Spring Boot provides a default error handling page and an error handling response in case of REST requests.

During the startup, Spring Boot looks up the /error endpoint. If there isn't any mapping configured then it configures a default fallback error page. This page is known as Whitelabel Error Page. Similarly, When working with REST requests, it provides a default JSON response in case of errors.

As you can see, The response from the default error handling page does not provide much information. This can be a problem when we are trying to debug the issue.

It is also problematic for front-end developers, who need detailed information on API error response messages to be able to explain to the end users what happened properly.

To solve this issue and make the API response messages more sophisticated, We can use Custom Exception Handling in the Spring Boot Application.

Custom Exception Handling

We have already seen the drawbacks of default error handling. Let us try to understand the other ways of handling the exceptions.

Try-Catch blocks

We can use the traditional try-catch block in the code which can catch the specified exception and provide us with a detailed error response message along with the status code.

Now we can see the valid status code, Which is 404 Not Found along with the message as API Response for the error.

But handling the exceptions for each API with a try-catch block might not be a good choice.

@ExceptionHandler Annotation

Spring provides @ExceptionHandler using which we can handle the exception in one method rather than having multiple try-catch blocks. Spring configuration will detect this annotation and register the method as an exception handler.

Add the below configuration in the LibraryController.class

When you try to add a book which is already present then the above code will handle the BookAlreadyExistsException in the controller class and provides the custom error message as defined.

This approach will handle the exceptions present in that controller, What if we have multiple controllers? We need to add the configuration in all the controller classes, which is again, not an optimal approach.

Global Exception Handling with @ControllerAdvice

The @ExceptionHandler is only limited to the particular class. If we need to handle the exceptions throughout the application then we have to make use of @ControllerAdvice of Spring AOP.

The Spring @ExceptionHandler along with @ControllerAdvice of Spring AOP will help us to handle the exceptions globally. The code for the GlobalExceptionHandler is as below.

@ControllerAdvice consolidates the multiple @ExceptionHandler into one single, global exception-handling component.

ResponseStatusException

Spring 5 has introduced the ResponseStatusException class. We can create an instance of it with Response status and optionally a reason and a throwable cause.

We have disabled the exception handler for BookAlreadyExistsException and modified the saveBook method to use the ResponseStatusException.

We need to add the property server.error.include-message=always in the application.properties file to include the error message as part of the JSON response.

We can use any of the approaches listed above based on the complexity of the project and the use case.

Congratulations ...๐ŸŽ‰ We have reached the end of our blog on Exception Handling in Spring Boot and also learned about Exception Handling and multiple ways to configure it in Spring Boot Application.

The source code is available on GitHub mentioned below

Subscribe to my Newsletter to stay updated with my blogs!! Happy Learning .. ๐Ÿ˜Š๐Ÿ‘

You can connect with me on Twitter and Linkedin

ย