“Best Practices for Centralized Exception Handling in Spring Boot: Handling UserNotFoundException in a Separate Class”

Marve Ike
2 min readOct 21, 2023

--

When building a web application using Spring Boot, it is inevitable that you will face exceptions at some point when processing requests. To handle exceptions, Spring Boot provides a way to use a global or centralized controller exception handling mechanism.

In the past, the most commonly used approach was to handle exceptions in individual controllers with the try-catch block. This approach is not scalable and can lead to code duplication since you need to write the same exception handlingcode multiple times if the same exception is thrown in different controllers. This is where centralized controller exception handling shines.

By using a centralized controller exception handling mechanism, you can handle all the exceptions in one place instead of copy-pasting code in multiple controllers.

Here is an example of how to handle exceptions using a centralized controller in Spring Boot:

#### java

@ControllerAdvice
public class ExceptionHandlerController {

@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleNotFound() {
return “not_found”;
}

@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String handleAccessDenied() {
return “access_denied”;
}

}

######

In the example above, we have created an `ExceptionHandlerController` class that uses the `@ControllerAdvice` annotation to indicate it will handle exceptions globally. There are two exception-handling methods defined within this class using the `@ExceptionHandler` annotation.

The first method is responsible for handling the `NotFoundException` and returns the HTTP response with a status code of 404 (NOT_FOUND) along with a web page containing an error message. The second method is responsible for handling the `AccessDeniedException` and returns the HTTP response with a status code of 401 (UNAUTHORIZED) along with a web page containing an error message.

Now, whenever a `NotFoundException` or `AccessDeniedException` occurs anywhere in the application, the corresponding exception handling method defined in the `ExceptionHandlerController` will handle it, and return an HTTP response with the appropriate status code and web page containing an error message.

In summary, using a centralized controller exception handling mechanism helps to separate the handling of exceptions from the controller’s business logic, making it more scalable and readable.

I love and thank for Always coming Back. Please #engage#like#follow#share#

#java #spring boot # #programming# #coding# #clean-code#

--

--

Marve Ike

Software engineer, writer & tech enthusiast. Co-founder of Brand Deals Hub. Passionate about simplifying complex tech topics & inspiring others. Let's connect!