@ControllerAdvice

In the Spring Framework for Java, the @ControllerAdvice annotation is used to define global controllers advice – pieces of code that are applied to all or a specific set of controllers. This annotation is particularly useful for handling exceptions across multiple controllers or providing common functionality.

Global Exception Handling: One of the main use cases for @ControllerAdvice is to centralize exception handling logic. By annotating a class with @ControllerAdvice, you can define methods that will be invoked when an exception is thrown within any controller method. This allows you to handle exceptions consistently across your application.

Model Attributes: @ControllerAdvice can also be used to define model attributes that should be added to all models across controllers. This can be useful for adding common attributes, such as user information, to every response.

Binding Result and InitBinder: It can be used to handle BindingResult and @InitBinder at a global level. BindingResult is typically used for form validation, and @InitBinder is used to customize request data binding.

Example for handling all exceptions

@ControllerAdvice
public class GlobalControllerAdvice {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        // Handle the exception and return an appropriate response
        return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Example for handling only a specific type of exception CustomerAlreadyExistsException

@ControllerAdvice  
public class GlobalExceptionHandler {  
  
    @ExceptionHandler(CustomerAlreadyExistsException.class)  
    public ResponseEntity<ErrorResponseDto> handleCustomerAlreadyExistsException(CustomerAlreadyExistsException exception,  
                                                                                 WebRequest webRequest){  
		// create a new responde dto
		...
		// return the response
        return new ResponseEntity<>(errorResponseDTO, HttpStatus.BAD_REQUEST);  
    }  
  
}