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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1@RestControllerAdvice lets you handle exceptions in one place instead of scattering try/catch across controllers.
- 2ProblemDetail gives every error a consistent, machine-readable shape with status, title, and custom properties.
- 3A catch-all Exception handler should log the cause and hide internal details behind a generic 500 message.
Related explainers
java
public List<String> collectTagsFromArticles(List<Article> articles) { return articles.stream() .flatMap(article -> article.getTags().stream()) .map(String::trim)
Flattening nested data with Java streams
streams
flatmap
collectors
Intermediate
7 steps
java
@Component @Order(20) public class ProductSearchIndexRunner implements ApplicationRunner {
Rebuilding a search index at Spring startup
startup-hook
batching
streaming
Intermediate
8 steps
java
public final class FileChecksum { private static final char[] HEX = "0123456789abcdef".toCharArray();
Streaming a SHA-256 file checksum in Java
hashing
streams
resource-management
Intermediate
7 steps
java
@Service public class OrderCheckoutService { private final OrderRepository orderRepository;
How @Transactional guards a Spring checkout
dependency-injection
transactions
atomicity
Intermediate
6 steps
java
@Service public class OrderMetricsService { private final MeterRegistry registry;
Instrumenting orders with Micrometer in Spring
metrics
micrometer
observability
Intermediate
8 steps
java
@RestController @RequestMapping("/api/files") public class FileUploadController {
Handling secure file uploads in Spring
file-upload
input-validation
path-traversal
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/centralized-error-handling-in-spring-explained-java-14c1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.