Performance: Why centralized error handling matters
Centralized error handling affects server response time and consistency, impacting how fast and reliably users receive error feedback.
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleAllExceptions(Exception e) { return ResponseEntity.status(500).body("Centralized error: " + e.getMessage()); } }
try { // business logic } catch (Exception e) { // handle error locally in each controller method return ResponseEntity.status(500).body("Error occurred"); }
| Pattern | Code Duplication | Response Time | Consistency | Verdict |
|---|---|---|---|---|
| Local try-catch in each method | High duplication | Slower on errors | Inconsistent | [X] Bad |
| Centralized @ControllerAdvice handler | No duplication | Faster on errors | Consistent | [OK] Good |
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNullPointer() {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Null value found");
}
What will be the HTTP status code and message when a NullPointerException occurs?@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAll(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred");
}
Why might this cause problems in a Spring Boot app?Pass the test and this pattern moves unknown