MODULE 5 · TOPIC 4 · VISUAL SPRING BOOT LAB

Spring Boot Global Exception Handling

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.

Why this step happens
See all steps in this scenario
    Java / Spring Boot configuration
    HTTP / application / test outputConsole
    Data operationsCompact blocks
    CurrentResultError / rejected

    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.

    Why this step happens
    See all steps in this scenario
      Java / Spring Boot configuration
      HTTP / application / test outputConsole
      Data operationsCompact blocks
      CurrentResultError / rejected

      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.

      Why this step happens
      See all steps in this scenario
        Java / Spring Boot configuration
        HTTP / application / test outputConsole
        Data operationsCompact blocks
        CurrentResultError / rejected

        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.

        Why this step happens
        See all steps in this scenario
          Java / Spring Boot configuration
          HTTP / application / test outputConsole
          Data operationsCompact blocks
          CurrentResultError / rejected

          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.

          Why this step happens
          See all steps in this scenario
            Java / Spring Boot configuration
            HTTP / application / test outputConsole
            Data operationsCompact blocks
            CurrentResultError / rejected

            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.

            Why this step happens
            See all steps in this scenario
              Java / Spring Boot configuration
              HTTP / application / test outputConsole
              Data operationsCompact blocks
              CurrentResultError / rejected

              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 / settingWhy and when to use it
              @RestControllerAdviceShare response-body handlers across controllers
              @ExceptionHandlerMap exception types to handler methods
              ProblemDetail.forStatusAndDetailCreate structured problem response
              @ValidTrigger Bean Validation on bound input
              MethodArgumentNotValidExceptionCommon invalid request body validation error
              HttpMessageNotReadableExceptionMalformed 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

              1. In a Boot Web project create StudentNotFound extends RuntimeException.
              2. Add the advice below in the scanned package with imports from org.springframework.http and org.springframework.web.bind.annotation.
              3. Throw new StudentNotFound() from an endpoint when lookup is empty.
              4. 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

              1. Add spring-boot-starter-validation to the Boot project.
              2. Define the DTO and mapping below; import jakarta.validation.Valid and jakarta.validation.constraints.NotBlank.
              3. Send {"name":""} and then {"name":"Anu"}.
              4. Customize the invalid body response with an exception handler if needed.
              Code / configuration
              record Input(@NotBlank String name) {}
              @PostMapping("/check")
              String check(@Valid @RequestBody Input input) { return input.name(); }
              Expected result: Blank input returns 400; valid input reaches the controller method.

              Predict the outcome before you run

              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.