Why this matters
- Scattered try-catch in controllers duplicates error handling and produces inconsistent JSON error shapes.
- RFC 7807 Problem Details give clients a standard error format with type, title, status, and detail.
- Global exception handling is a production requirement — unhandled exceptions should never leak stack traces.
@ControllerAdvice
L1 · FresherCentral handlers translate exceptions to consistent JSON error bodies for every controller in BookStore.
Problem Details (RFC 7807)
L2 · IntermediateEnable spring.mvc.problemdetails.enabled=true for structured type, title, status, and detail fields.
@ExceptionHandler scope
L3 · AdvancedMethod-level handlers override class-level ones. Map BookNotFoundException to 404 and validation errors to 400 with field details.
Security exceptions
L4 · ExpertSpring Security throws specialized exceptions — either handle in security entry points or map in advice without leaking stack traces.
Domain exceptions
// learn:fragment
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(Long id) {
super("Book not found with id: " + id);
}
}
public class DuplicateIsbnException extends RuntimeException {
public DuplicateIsbnException(String isbn) {
super("Book with ISBN " + isbn + " already exists");
}
}
Services throw domain exceptions; controllers stay clean.
Global exception handler
// learn:fragment
@RestControllerAdvice
public class BookStoreExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail handleNotFound(BookNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Book Not Found");
problem.setType(URI.create("https://bookstore.example.com/errors/not-found"));
return problem;
}
@ExceptionHandler(DuplicateIsbnException.class)
public ProblemDetail handleDuplicate(DuplicateIsbnException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.CONFLICT, ex.getMessage());
problem.setTitle("Duplicate ISBN");
return problem;
}
}
ProblemDetail (Spring 6+) implements RFC 7807 natively.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 6 sections
- Validation errors
- Catch-all handler
- @ResponseStatus on the exception
- Controller stays clean
- ResponseEntity alternative
- Testing exception handling
Test yourself
Answer these before moving on — recall is what makes it stick.