Spring Boot & Microservices (50 Qs)•Part 1: Spring Core, Auto-Configuration & Architecture (1 - 10)
How do you handle Global Exceptions in Spring Boot REST APIs?
senior LevelCode ExampleSystem DesignHTTP & REST APIs
In Simple Words:
Use @RestControllerAdvice and @ExceptionHandler to intercept exceptions across all controllers and return standardized RFC-7807 ProblemDetail or structured error payloads.
java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ProblemDetail> handleNotFound(ResourceNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Resource Not Found");
problem.setProperty("timestamp", Instant.now());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problem);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
return ResponseEntity.badRequest().body(errors);
}
}