Performance: ResponseEntityExceptionHandler
This affects server response time and client perceived latency by centralizing exception handling and controlling HTTP responses.
@ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { // custom error response return super.handleExceptionInternal(ex, body, headers, status, request); } }
try { // controller logic } catch (Exception e) { return new ResponseEntity<>("Error", HttpStatus.INTERNAL_SERVER_ERROR); }
| Pattern | Exception Handling Logic | Response Consistency | Server CPU Usage | Verdict |
|---|---|---|---|---|
| Scattered try-catch in controllers | Multiple per controller | Inconsistent | High due to duplication | [X] Bad |
| Centralized ResponseEntityExceptionHandler | Single global handler | Consistent | Lower due to reuse | [OK] Good |
ResponseEntityExceptionHandler in a Spring Boot application?ResponseEntityExceptionHandler to handle MethodArgumentNotValidException?ResponseEntityExceptionHandler:
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String body = "Malformed JSON request";
return new ResponseEntity<>(body, headers, HttpStatus.BAD_REQUEST);
}
What will be the HTTP status code returned when a malformed JSON is sent to the API? @ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<Object> handleNullPointer(NullPointerException ex, WebRequest request) {
String body = "Null value found";
return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
String body = "Validation failed";
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}
If a NullPointerException occurs, what will be the HTTP status code returned?ResponseEntityExceptionHandler methods and @ExceptionHandler to achieve this?Pass the test and this pattern moves unknown