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 final class CircuitBreaker { private enum State { CLOSED, OPEN, HALF_OPEN }
How a circuit breaker guards failing calls
state-machine
resilience
concurrency
Advanced
7 steps
java
public Map<Long, CustomerDto> indexByCustomerId(List<CustomerDto> customers) { return customers.stream() .collect(Collectors.toMap( CustomerDto::getId,
Building maps from lists with Collectors.toMap
streams
collectors
maps
Intermediate
5 steps
java
@Service public class InventoryService { private final RestClient warehouseClient;
Bulkhead-protected HTTP calls in Spring
bulkhead
resilience
fallback
Intermediate
7 steps
rust
use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use axum::body::Body;
A maintenance-mode gate in Axum
middleware
shared-state
atomics
Intermediate
7 steps
java
@Configuration public class DataSourceLoggingConfig { @Bean
Wrapping a Spring DataSource for query tracing
proxy pattern
observability
data source
Intermediate
7 steps
java
@RestController @RequestMapping("/api/products") @Validated public class ProductSearchController {
Validating query params in a Spring controller
validation
pagination
rest-api
Intermediate
8 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.