Performance: @ControllerAdvice for global handling
This affects server response time and error handling efficiency, impacting how fast and smoothly error responses are generated and sent to the client.
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage()); } } @RestController public class UserController { @GetMapping("/user/{id}") public User getUser(@PathVariable String id) { // fetch user without try-catch } }
@RestController public class UserController { @GetMapping("/user/{id}") public ResponseEntity<User> getUser(@PathVariable String id) { try { // fetch user } catch (UserNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } return ResponseEntity.ok(user); } // similar try-catch in every controller method }
| Pattern | Code Duplication | CPU Usage | Response Time Impact | Verdict |
|---|---|---|---|---|
| Try-catch in every controller method | High | Higher due to repeated handling | Slightly slower under load | [X] Bad |
| Centralized @ControllerAdvice handling | Low | Lower due to single handling point | Faster and more consistent | [OK] Good |
@ControllerAdvice in a Spring Boot application?@ControllerAdvice class?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);
}
}@ControllerAdvice class:@ControllerAdvice
public class GlobalHandler {
@ExceptionHandler(IllegalArgumentException.class)
public String handleIllegalArgument() {
return "illegal";
}
@ExceptionHandler(Exception.class)
public String handleAll() {
return "error";
}
}NullPointerException occurs in a controller?ResourceNotFoundException, which should return 404 status with a custom message. How should you implement this using @ControllerAdvice?Pass the test and this pattern moves unknown