@ControllerAdvice helps you handle errors or special cases in one place for all your web controllers. It keeps your code clean and organized.
@ControllerAdvice for global handling in 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.
@ControllerAdvice public class GlobalHandler { @ExceptionHandler(NullPointerException.class) public ResponseEntity<String> handleNullPointer(NullPointerException ex) { return new ResponseEntity<>("Null value found", HttpStatus.BAD_REQUEST); } }
@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); } }
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.
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); } }
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.
@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.