Global exception handling centralizes how application failures become HTTP responses. A controller or service throws a meaningful exception; MVC exception resolvers select a matching local or advice handler. @RestControllerAdvice combines controller advice with response-body semantics. ProblemDetail gives clients a structured error format. Security filter failures and errors outside the MVC dispatch need their own handling.
Browser-based Spring Boot simulations. Change inputs and trace HTTP requests, bean wiring, SQL, security decisions and tests. No real Java, HTTP server or database operations are executed.
1. Exception propagation — controller, service and advice
A domain exception can travel from a service through the controller to DispatcherServlet exception resolution. A matching handler converts it into an HTTP response. Normal return does not pass through an exception handler.
Why this example? Trace a normal request and a missing resource exception through the same layers.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
A domain exception can travel from a service through the controller to DispatcherServlet exception resolution. A matching handler converts it into an HTTP response. Normal return does not pass through an exception handler.
Try and observe
Observe where the exception jumps to advice instead of producing normal JSON.
2. Validation and malformed JSON
JSON conversion happens before a controller method is invoked. An unreadable body produces a conversion error. If conversion succeeds, Bean Validation constraints on @Valid DTOs can reject invalid fields. These are different failure stages.
Why this example? Compare malformed JSON, a blank field and valid input.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
JSON conversion happens before a controller method is invoked. An unreadable body produces a conversion error. If conversion succeeds, Bean Validation constraints on @Valid DTOs can reject invalid fields. These are different failure stages.
Try and observe
Change request body and identify the first failing stage.
3. Exception handler specificity
Within the same advice, Spring MVC searches for a matching handler and prefers a more specific exception mapping for a direct exception. Handler selection across ordered advice beans or nested causes has additional rules. Avoid broad handlers that conceal meaningful HTTP errors.
Why this example? Compare a StudentNotFound exception with a generic unexpected runtime error.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
Within the same advice, Spring MVC searches for a matching handler and prefers a more specific exception mapping for a direct exception. Handler selection across ordered advice beans or nested causes has additional rules. Avoid broad handlers that conceal meaningful HTTP errors.
Try and observe
Observe different handler methods and status codes.
4. ProblemDetail and safe error information
ProblemDetail represents standardized error information such as type, title, status, detail and instance. Public error descriptions should be actionable without exposing stack traces or internal connection strings. Log the original exception separately with a correlation identifier.
Why this example? Compare a safe public error body with a rejected verbose design.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
ProblemDetail represents standardized error information such as type, title, status, detail and instance. Public error descriptions should be actionable without exposing stack traces or internal connection strings. Log the original exception separately with a correlation identifier.
Try and observe
Inspect the response fields and which diagnostic details remain on the server.
5. Transaction rollback and exception mapping
An exception escaping a transactional service normally triggers rollback for unchecked exceptions. A web advice maps the failure after the service boundary. Catching and swallowing errors inside a transaction can change rollback behavior; database failures can also mark a transaction rollback-only.
Why this example? Observe a successful write and an unchecked failure after staging a write.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
An exception escaping a transactional service normally triggers rollback for unchecked exceptions. A web advice maps the failure after the service boundary. Catching and swallowing errors inside a transaction can change rollback behavior; database failures can also mark a transaction rollback-only.
Try and observe
Compare committed records rather than just response status.
6. Status code mapping — distinguish client and server errors
HTTP 400 means a client request is invalid, 404 means the requested resource is missing, 409 represents a state conflict, and 500 indicates an unexpected server failure. A single catch-all status makes retry and client correction difficult.
Why this example? Select an error and trace the handler and recommended client action.
Concept flowchart
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Current stepSelected path / resultDecision
Why this step happens
See all steps in this scenario
Java / Spring Boot configuration
HTTP / application / test outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Database rows
Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.
What this animation explains
HTTP 400 means a client request is invalid, 404 means the requested resource is missing, 409 represents a state conflict, and 500 indicates an unexpected server failure. A single catch-all status makes retry and client correction difficult.
Try and observe
Compare invalid input, duplicate logical key and internal failure.
API and configuration reference
Refer to these APIs and settings while building a real Spring project.
API / setting
Why and when to use it
@RestControllerAdvice
Share response-body handlers across controllers
@ExceptionHandler
Map exception types to handler methods
ProblemDetail.forStatusAndDetail
Create structured problem response
@Valid
Trigger Bean Validation on bound input
MethodArgumentNotValidException
Common invalid request body validation error
HttpMessageNotReadableException
Malformed or unreadable request body
Worked practical examples
Follow these procedures with the Java 21 / Spring Boot 3.4.0 teaching project. Unless complete files are provided, the code is a focused snippet requiring the indicated imports, companion classes and configuration.
1. Centralize a missing student response
Procedure
In a Boot Web project create StudentNotFound extends RuntimeException.
Add the advice below in the scanned package with imports from org.springframework.http and org.springframework.web.bind.annotation.
Throw new StudentNotFound() from an endpoint when lookup is empty.
Call an absent ID and inspect status and JSON.
Code / configuration
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(StudentNotFound.class)
ResponseEntity<ProblemDetail> notFound(StudentNotFound ex) {
ProblemDetail p=ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND,"Student not found");
return ResponseEntity.status(404).body(p);
}
}
Expected result: HTTP 404 with a ProblemDetail body; the controller no longer duplicates error formatting.
2. Validate incoming JSON
Procedure
Add spring-boot-starter-validation to the Boot project.
Define the DTO and mapping below; import jakarta.validation.Valid and jakarta.validation.constraints.NotBlank.
Send {"name":""} and then {"name":"Anu"}.
Customize the invalid body response with an exception handler if needed.
Try answering these questions, then expand each answer and repeat the appropriate simulation.
1. Predict the outcome for Missing student in Exception propagation — controller, service and advice. Which path is taken and why?
Advice sets status and body. Expected state: 404 Not Found.
2. Predict the outcome for IllegalStateException in Exception handler specificity. Which path is taken and why?
Internal failure is not a missing resource. Expected state: 500.
3. Predict the outcome for Audit throws unchecked in Transaction rollback and exception mapping. Which path is taken and why?
An HTTP error is mapped outside the transaction. Expected state: 500.
Hands-on practice and assessment
Programming challenge
Create a custom not-found exception, a REST advice and a validated DTO. Trigger missing resource, invalid JSON and validation errors; compare HTTP status and structured responses.
Edit this practice scratchpad and copy it into your real Java project. The browser does not compile arbitrary Java.
Quick assessment
Key points and real Spring notes
Avoid leaking stack traces, credentials or database details. Log internal diagnostic context separately; do not map all failures to 200.