JavaSpring Boot

How to use @ControllerAdvice annotation in a spring boot app

The @ControllerAdvice annotation in Spring Boot is a powerful mechanism for centralizing exception handling and model attribute advice across multiple controllers. It allows you to define methods that are shared across multiple controllers to handle exceptions or add model attributes. This can improve code organization, reduce redundancy, and enhance maintainability in a Spring Boot application. In this post we will understand How to use @ControllerAdvice annotation in a spring boot app.

Overview of @ControllerAdvice

Annotation Declaration:

The @ControllerAdvice annotation is used at the class level to indicate that the annotated class plays the role of a controller advice.

@ControllerAdvice
public class GlobalControllerAdvice {
    // Advice methods go here
}

Exception Handling:

One common use of @ControllerAdvice is to handle exceptions globally. You can define methods within the annotated class to handle specific exceptions.

@ControllerAdvice
public class GlobalControllerAdvice {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        // Custom logic for handling exceptions
        return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Model Attributes:

Another use case is to provide model attributes that are shared across multiple controllers. This is useful for adding common data to the model before rendering views.

@ControllerAdvice
public class GlobalControllerAdvice {

    @ModelAttribute("globalAttribute")
    public String globalAttribute() {
        return "This is a global attribute";
    }
}

Example: Using @ControllerAdvice

Let’s consider a simple Spring Boot application with multiple controllers. We want to handle a custom exception globally and provide a common model attribute.

Custom Exception:

public class CustomException extends RuntimeException {
    // Custom exception details go here
}

Controller 1:

@RestController
public class Controller1 {

    @GetMapping("/controller1")
    public String controller1() {
        throw new CustomException();
    }
}

Controller 2:

@RestController
public class Controller2 {

    @GetMapping("/controller2")
    public String controller2() {
        // Controller logic
        return "Controller 2 response";
    }
}

Global Controller Advice:

@ControllerAdvice
public class GlobalControllerAdvice {

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<String> handleCustomException(CustomException e) {
        return new ResponseEntity<>("Custom Exception occurred: " + e.getMessage(), HttpStatus.BAD_REQUEST);
    }

    @ModelAttribute("globalAttribute")
    public String globalAttribute() {
        return "This is a global attribute";
    }
}

In this example, when an exception of type CustomException occurs in any controller, the handleCustomException method in GlobalControllerAdvice will be invoked to handle it. Additionally, the globalAttribute method adds a common attribute to the model for all controllers.

Real-world Uses:

Consistent Error Handling: @ControllerAdvice helps maintain a consistent approach to handling errors across the entire application.

Global Attributes: Providing common model attributes is useful for adding global information to views, such as user authentication status or application-wide settings.

Code Organization: Centralizing exception handling and model attribute advice improves code organization and makes it easier to manage concerns that span multiple controllers.

In summary, @ControllerAdvice in Spring Boot is a valuable tool for centralizing exception handling and model attribute advice, leading to cleaner, more maintainable code in real-world applications.

In the last BitsToGigs post we had discussed How to use @Transactional annotation in a spring boot application

Happy Learning!


Subscribe to the BitsToGigs Newsletter

What's your reaction?

Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0

You may also like

More in:Java

Leave a reply

Your email address will not be published. Required fields are marked *