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
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
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.