Sobes.tech
Junior — Middle

Could you explain the purpose and use of the @ControllerAdvice annotation in Spring?

sobes.tech AI

Answer from AI

The @ControllerAdvice annotation in Spring is used for global exception handling, configuring model data, and intercepting requests across all controllers in the application. This allows centralized error handling and the application of common settings without duplicating code in each controller.

For example, with @ControllerAdvice, you can define a method that handles exceptions of type Exception across all controllers:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleAllExceptions(Exception ex) {
        return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Thus, when an exception occurs in any controller, this method will be automatically invoked, ensuring uniform error handling.

Could you explain the purpose and use of the… - sobes.tech