0
0
Spring Bootframework~5 mins

@ControllerAdvice for global handling in Spring Boot

Choose your learning style9 modes available
Introduction

@ControllerAdvice helps you handle errors or special cases in one place for all your web controllers. It keeps your code clean and organized.

You want to show a friendly error message for all errors in your app.
You need to log exceptions from any controller in one place.
You want to customize the response when a user sends bad data.
You want to apply the same rules or responses for multiple controllers.
You want to handle specific exceptions globally without repeating code.
Syntax
Spring Boot
@ControllerAdvice
public class GlobalExceptionHandler {

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

@ControllerAdvice marks the class as a global handler for controllers.

@ExceptionHandler inside it defines which exceptions to catch and handle.

Examples
This handles only NullPointerException globally and returns a 400 error.
Spring Boot
@ControllerAdvice
public class GlobalHandler {

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handleNullPointer(NullPointerException ex) {
        return new ResponseEntity<>("Null value found", HttpStatus.BAD_REQUEST);
    }
}
This handles multiple exception types in one method.
Spring Boot
@ControllerAdvice
public class GlobalHandler {

    @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
    public ResponseEntity<String> handleBadRequests(RuntimeException ex) {
        return new ResponseEntity<>("Bad request: " + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
Sample Program

This example has a controller that throws an error when you visit /error. The @ControllerAdvice class catches that error and returns a friendly message with status 500.

Spring Boot
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @GetMapping("/error")
    public String throwError() {
        throw new RuntimeException("Something went wrong");
    }
}

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return new ResponseEntity<>("Global error handled: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
OutputSuccess
Important Notes

You can have multiple @ExceptionHandler methods for different exceptions.

@ControllerAdvice can also be used to add global data to all controllers or handle validation errors.

Make sure your exception handler methods return proper HTTP status codes for better API design.

Summary

@ControllerAdvice lets you handle errors for all controllers in one place.

Use @ExceptionHandler inside it to catch specific exceptions globally.

This keeps your code clean and improves user experience with consistent error messages.