@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.
Practice
@ControllerAdvice in a Spring Boot application?Solution
Step 1: Understand the role of @ControllerAdvice
@ControllerAdvice is a special annotation in Spring Boot that allows you to write code to handle exceptions or apply logic across all controllers globally.Step 2: Identify its main use
Its main use is to centralize exception handling so you don't have to repeat error handling code in every controller.Final Answer:
To handle exceptions globally for all controllers in one place -> Option AQuick Check:
@ControllerAdvice = global exception handling [OK]
- Confusing @ControllerAdvice with @RestController
- Thinking it configures database or tasks
- Assuming it defines endpoints
@ControllerAdvice class?Solution
Step 1: Identify the annotation for exception handling
The correct annotation to handle exceptions globally is @ExceptionHandler with the exception class specified.Step 2: Check method signature and annotation usage
@ExceptionHandler(Exception.class) public String handleError() { return "error"; } uses @ExceptionHandler(Exception.class) which is correct inside a @ControllerAdvice class to catch all exceptions.Final Answer:
@ExceptionHandler(Exception.class) public String handleError() { return "error"; } -> Option BQuick Check:
@ExceptionHandler = global exception method [OK]
- Using @RequestMapping or @GetMapping instead of @ExceptionHandler
- Missing exception class in @ExceptionHandler
- Using @Service annotation incorrectly
NullPointerException is thrown in any controller?@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNullPointer() {
return new ResponseEntity<>("Null pointer error", HttpStatus.BAD_REQUEST);
}
}Solution
Step 1: Analyze the @ExceptionHandler method
The method handles NullPointerException and returns a ResponseEntity with message "Null pointer error" and status BAD_REQUEST.Step 2: Understand HTTP status returned
HttpStatus.BAD_REQUEST corresponds to 400 status code, so the response will have status 400 with the given message.Final Answer:
400 Bad Request with message "Null pointer error" -> Option AQuick Check:
@ExceptionHandler returns 400 status [OK]
- Assuming default 500 error instead of specified status
- Confusing 400 with 200 OK
- Ignoring the returned ResponseEntity status
@ControllerAdvice class:@ControllerAdvice
public class GlobalHandler {
@ExceptionHandler(IllegalArgumentException.class)
public String handleIllegalArgument() {
return "illegal";
}
@ExceptionHandler(Exception.class)
public String handleAll() {
return "error";
}
}What is the problem if a
NullPointerException occurs in a controller?Solution
Step 1: Identify exception handlers and their scopes
handleIllegalArgument() handles IllegalArgumentException only; handleAll() handles all Exceptions as a fallback.Step 2: Determine which method handles NullPointerException
Since NullPointerException is not IllegalArgumentException, handleAll() will catch it as it handles Exception class.Final Answer:
handleAll() method will handle NullPointerException correctly -> Option CQuick Check:
More specific handlers first, then general Exception handler [OK]
- Thinking NullPointerException is unhandled
- Assuming multiple handlers cause compile error
- Confusing which handler matches which exception
ResourceNotFoundException, which should return 404 status with a custom message. How should you implement this using @ControllerAdvice?Solution
Step 1: Understand requirement for specific and general handling
You need one handler for ResourceNotFoundException with 404 and custom JSON, and another for all other exceptions with generic 500 JSON.Step 2: Implement two separate @ExceptionHandler methods in @ControllerAdvice
One method annotated with @ExceptionHandler(ResourceNotFoundException.class) returns 404 JSON; another with @ExceptionHandler(Exception.class) returns 500 JSON.Final Answer:
Create two @ExceptionHandler methods: one for ResourceNotFoundException returning 404 JSON, another for Exception returning generic JSON with 500 status -> Option DQuick Check:
Separate handlers for specific and general exceptions [OK]
- Using one method with manual type checks inside
- Handling specific exceptions in controllers, not globally
- Ignoring general exceptions in @ControllerAdvice
Ready to prove it?
Pass the test and this pattern moves unknown
