java 48 lines · 7 steps

Centralized error handling in Spring

A single advice class maps each exception type to a standardized RFC 7807 ProblemDetail response.

Explained by highlit
1@RestControllerAdvice
2public class GlobalExceptionHandler {
3 
4 private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
5 
6 @ExceptionHandler(ResourceNotFoundException.class)
7 public ResponseEntity<ProblemDetail> handleNotFound(ResourceNotFoundException ex) {
8 ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
9 body.setTitle("Resource Not Found");
10 body.setProperty("resourceId", ex.getResourceId());
11 return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
12 }
13 
14 @ExceptionHandler(DuplicateResourceException.class)
15 public ResponseEntity<ProblemDetail> handleDuplicate(DuplicateResourceException ex) {
16 ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
17 body.setTitle("Resource Already Exists");
18 return ResponseEntity.status(HttpStatus.CONFLICT).body(body);
19 }
20 
21 @ExceptionHandler(MethodArgumentNotValidException.class)
22 public ResponseEntity<ProblemDetail> handleValidation(MethodArgumentNotValidException ex) {
23 Map<String, String> errors = new HashMap<>();
24 for (FieldError error : ex.getBindingResult().getFieldErrors()) {
25 errors.put(error.getField(), error.getDefaultMessage());
26 }
27 ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
28 body.setTitle("Invalid Request");
29 body.setProperty("errors", errors);
30 return ResponseEntity.badRequest().body(body);
31 }
32 
33 @ExceptionHandler(BusinessRuleException.class)
34 public ResponseEntity<ProblemDetail> handleBusinessRule(BusinessRuleException ex) {
35 ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_ENTITY, ex.getMessage());
36 body.setTitle("Business Rule Violation");
37 body.setProperty("code", ex.getCode());
38 return ResponseEntity.unprocessableEntity().body(body);
39 }
40 
41 @ExceptionHandler(Exception.class)
42 public ResponseEntity<ProblemDetail> handleUnexpected(Exception ex) {
43 log.error("Unhandled exception", ex);
44 ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
45 body.setTitle("Internal Server Error");
46 return ResponseEntity.internalServerError().body(body);
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1@RestControllerAdvice lets you handle exceptions in one place instead of scattering try/catch across controllers.
  2. 2ProblemDetail gives every error a consistent, machine-readable shape with status, title, and custom properties.
  3. 3A catch-all Exception handler should log the cause and hide internal details behind a generic 500 message.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Centralized error handling in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code