Performance: @ControllerAdvice for global handling
MEDIUM IMPACT
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 |