# josamvkd/global-exception-handling architecture

> Architecture diagram of the GitHub repository josamvkd/global-exception-handling, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-12). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/josamvkd/global-exception-handling
- Repository: https://github.com/josamvkd/global-exception-handling

## Overview

##### Project type & purpose (what you’re diagramming)
This repo is a **single-service Spring Boot 4 REST API** (Java 21, Maven) that demonstrates **global exception handling** for a simple **Product CRUD** domain using **Spring Web + Spring Data JPA + Bean Validation** and an in-memory **H2** database (README mentions MySQL, but run instructions show H2 console and an H2 JDBC URL).

So the “system” is primarily:
- One HTTP API service
- One relational database (H2 in dev/demo; optionally MySQL)
- A clear internal layering: **Controller → Service → Repository → DB**
- A cross-cutting concern: **GlobalExceptionHandler (@RestControllerAdvice)** + validation pipeline producing a unified `ApiErrorResponse`

From `src/main/java/com/josamtechie/api/...`:

##### Runtime entry points / configuration
- `GlobalExceptionHandlingApplication.java` — Spring Boot application entrypoint (component scan / auto-config).
- `application.properties` — environment configuration (DB URL, JPA settings, etc.).
- `DataInitializer.java` — seeds sample data at startup (important “startup-time flow”).

##### Web/API layer
- `controller/ProductController.java` — REST endpoints: `/api/products` CRUD.

##### Business layer
- `service/ProductService.java` — business logic and deliberate exception throws.
- This is where `BusinessException`, `DuplicateResourceException`, `ResourceNotFoundException` originate.

##### Persistence layer
- `repository/ProductRepository.java` — Spring Data JPA repository.
- `model/Product.java` — JPA entity + Bean Validation annotations.

##### DTO and error model
- `dto/ProductRequest.java` — request payload (Java Record) with validation.
- `dto/ApiErrorResponse.java` — unified error payload (record, nested record for field errors).

##### Exception handling (cross-cutting)
- `exception/GlobalExceptionHandler.java` — the core of the demo: maps exceptions to HTTP responses.
- `exception/*Exception.java` — domain/business exceptions.

##### Tests
- `GlobalExceptionHandlingApplicationTests.java` — indicates at least a Spring Boot test context (optionally include in a “Dev/Test” view, not the runtime system view).

##### Normal request path (success)
Client → `ProductController` → `ProductService` → `ProductRepository` → DB
Then response returns back up the chain.

##### Error/exception path (the point of this repo)
Exceptions can arise from:
- **Controller binding/validation**: `MethodArgumentNotValidException`, `HttpMessageNotReadableException`, `MethodArgumentTypeMismatchException`
- **Service/domain**: `ResourceNotFoundException`, `DuplicateResourceException`, `BusinessException`
- **Framework routing**: `NoResourceFoundException`, `HttpRequestMethodNotSupportedException`
- **Catch-all**: `Exception`

All of these are intercepted by:
- `GlobalExceptionHandler (@RestControllerAdvice)` → returns `ApiErrorResponse` with correct HTTP status.

##### Database (H2 in-memory for demo; optionally MySQL as alternative)
4. (Optional) **H2 Console** as a browser-accessible tool hitting the DB (only in dev profile)

- Client → API Service: `HTTP/JSON` (`/api/products`)
- API Service → DB: `JDBC` via `JPA/Hibernate`
- (Optional) Browser → H2 Console: HTTP
- H2 Console → DB: JDBC/internal connection

**Why this matters:** it matches how the app is actually run (`./mvnw spring-boot:run`) and used (HTTP calls + DB).

**Goal:** show the internal architecture and exception flow.

Break the “API Service” container into components:

##### Web Layer
- `ProductController`

##### Validation & Binding (pipeline)
- Bean Validation (`@Valid`) on `ProductRequest`
- Message conversion (JSON → record) (source of `HttpMessageNotReadableException`)
- Path variable binding (source of `MethodArgumentTypeMismatchException`)

##### Business Layer
- `ProductService`

##### Persistence Layer
- `ProductRepository` (Spring Data JPA)
- `Product` entity
- JPA provider (Hibernate) (optional but helpful label)

##### Exception Handling (cross-cutting)
- `GlobalExceptionHandler` producing `ApiErrorResponse`
- Custom exceptions: `ResourceNotFoundException`, `DuplicateResourceException`, `BusinessException`

##### Startup/Data Seeding
- `DataInitializer` → `ProductRepository` (or service, depending on implementation) → DB

- Client → Controller: `POST/GET/PUT/DELETE /api/products`
- Controller → Service: method calls (`createProduct`, `getProductById`, etc.)
- Service → Repository: CRUD operations
- Repository → DB: persistence operations
- Service → throws → (caught by) GlobalExceptionHandler
- Controller/binding/validation → throws → GlobalExceptionHandler
- Framework routing/method mismatch → GlobalExceptionHandler
- GlobalExceptionHandler → Client: `ApiErrorResponse (status, error, message, path, timestamp, fieldErrors[])`

**This repo’s “money shot”:** make it visually obvious that *many exception sources funnel into one handler* that standardizes responses.

##### Request lifecycle (failure)
Same path, but at any stage an exception is thrown and intercepted by:
- `GlobalExceptionHandler` → builds `ApiErrorResponse` → returns correct HTTP status

##### Data initialization lifecycle
On startup:
- Spring Boot starts → `DataInitializer` runs → inserts products via repository/service → DB contains sample records.

##### Architectural patterns/design principles evident here (call them out
- **Layered architecture**: Controller (presentation) → Service (domain/business) → Repository (data access)
- **DTO boundary**: `ProductRequest` separates API contract from persistence entity `Product`
- **Centralized error handling**: `@RestControllerAdvice` produces a single error schema (`ApiErrorResponse`)
- **Explicit domain exceptions**: makes business rules readable and testable (`BusinessException`, etc.)

At minimum label:
- **Spring Boot 4**
- **Spring Web / Spring MVC**
- **Spring Data JPA**
- **Bean Validation (Jakarta Validation)**
- **H2 (demo) / MySQL (optional target)**
- **Maven** (build/run)

- **Hibernate** as JPA provider

##### Container View (Client ↔ Spring Boot Service ↔ DB)
2. **Component View of Spring Boot Service** (Controller/Service/Repository + Validation + GlobalExceptionHandler + DTOs)

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================================================
    %% SECTION 1: CONTAINER VIEW (runtime)
    %% =========================================================
    subgraph "Container View (Runtime)"
        direction TB

        Client["API Client\n(curl/Postman/Browser)"]:::external

        subgraph "Spring Boot API Service (Single Container)"
            direction TB
            App["Spring Boot 4 REST API\n(Java 21, Maven)\nSpring Web + Spring Data JPA + Bean Validation"]:::infra
            Config["Application Config\n(application.properties)\nDB/JPA settings"]:::infra
        end

        DBH2[("H2 Database\n(in-memory/demo)")]:::db
        DBMySQL[("MySQL Database\n(optional target)")]:::db

        H2Console["H2 Console\n(dev tool)"]:::external

        Client -->|"HTTP/JSON\n/api/products"| App
        App -->|"JDBC via JPA/Hibernate"| DBH2
        App -.->|"JDBC via JPA/Hibernate\n(optional)"| DBMySQL

        Client -.->|"HTTP (dev)"| H2Console
        H2Console -->|"DB access"| DBH2
        Config -->|"configures"| App
    end

    %% =========================================================
    %% SECTION 2: COMPONENT VIEW (inside Spring Boot service)
    %% =========================================================
    subgraph "Component View (Inside Spring Boot Service)"
        direction TB

        subgraph "Spring Runtime"
            direction TB
            Boot["Spring Boot Application\n(component scan, auto-config)"]:::infra
            MVC["Spring MVC\nDispatcherServlet"]:::infra
        end

        subgraph "Web/API Layer"
            direction TB
            ProductController["ProductController\nREST endpoints\n/api/products (CRUD)"]:::web
        end

        subgraph "Binding & Validation Pipeline"
            direction TB
            MsgConv["JSON Message Conversion\n(request body -> DTO)\n(e.g., HttpMessageNotReadableException)"]:::infra
            PathBind["Path/Param Binding\n(e.g., MethodArgumentTypeMismatchException)"]:::infra
            Validation["Bean Validation (@Valid)\n(e.g., MethodArgumentNotValidException)"]:::infra
            ProductRequest["ProductRequest DTO\n(validated request payload)"]:::dto
        end

        subgraph "Business Layer"
            direction TB
            ProductService["ProductService\nbusiness rules\nthrows domain exceptions"]:::service
            BizEx["BusinessException"]:::exception
            DupEx["DuplicateResourceException"]:::exception
            NotFoundEx["ResourceNotFoundException"]:::exception
        end

        subgraph "Persistence Layer"
            direction TB
            ProductRepository["ProductRepository\nSpring Data JPA"]:::repo
            ProductEntity["Product Entity\n(JPA + validation annotations)"]:::model
            Hibernate["JPA Provider\n(Hibernate)"]:::infra
        end

        subgraph "Cross-cutting: Global Exception Handling"
            direction TB
            GlobalHandler["GlobalExceptionHandler\n@RestControllerAdvice\nmaps exceptions -> HTTP responses"]:::exception
            ApiError["ApiErrorResponse DTO\nunified error schema\n(status,error,message,path,timestamp,fieldErrors[])"]:::dto
        end

        subgraph "Startup Lifecycle"
            direction TB
            DataInit["DataInitializer\nseeds sample data at startup"]:::infra
        end

        DB2[("Relational DB\nH2 (demo) / MySQL (optional)")]:::db

        %% Normal request flow (success)
        Client2["API Client"]:::external
        Client2 -->|"HTTP/JSON\nPOST/GET/PUT/DELETE /api/products"| MVC
        MVC -->|"dispatches"| ProductController
        ProductController -->|"binds request"| MsgConv
        MsgConv -->|"creates DTO"| ProductRequest
        ProductController -->|"binds params"| PathBind
        ProductRequest -->|"@Valid"| Validation
        ProductController -->|"calls"| ProductService
        ProductService -->|"CRUD ops"| ProductRepository
        ProductRepository -->|"maps entity"| ProductEntity
        ProductRepository -->|"JPA persistence"| Hibernate
        Hibernate -->|"JDBC"| DB2
        ProductController -->|"HTTP/JSON\n(success response)"| Client2

        %% Startup/data seeding flow
        Boot -->|"starts application"| MVC
        Boot -->|"runs on startup"| DataInit
        DataInit -->|"inserts seed data"| ProductRepository
        Hibernate -->|"JDBC"| DB2

        %% Exception funnel (dashed red)
        ProductController -.->|"throws binding/validation errors"| GlobalHandler
        MsgConv -.->|"throws HttpMessageNotReadableException"| GlobalHandler
        PathBind -.->|"throws MethodArgumentTypeMismatchException"| GlobalHandler
        Validation -.->|"throws MethodArgumentNotValidException"| GlobalHandler

        ProductService -.->|"throws"| BizEx
        ProductService -.->|"throws"| DupEx
        ProductService -.->|"throws"| NotFoundEx

        BizEx -.->|"handled by"| GlobalHandler
        DupEx -.->|"handled by"| GlobalHandler
        NotFoundEx -.->|"handled by"| GlobalHandler

        MVC -.->|"routing errors\n(e.g., HttpRequestMethodNotSupportedException,\nNoResourceFoundException)"| GlobalHandler
        ProductRepository -.->|"unexpected errors"| GlobalHandler
        GlobalHandler -->|"builds"| ApiError
        ApiError -->|"HTTP/JSON\nerror response"| Client2
    end

    %% =========================================================
    %% OPTIONAL: DEV/TEST SIGNAL
    %% =========================================================
    subgraph "Dev/Test"
        direction TB
        Tests["Spring Boot Test Context\n(smoke test)"]:::test
    end

    %% =========================================================
    %% Click Events (from component_mapping)
    %% =========================================================
    click Boot "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/GlobalExceptionHandlingApplication.java"
    click Config "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/resources/application.properties"
    click DataInit "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/DataInitializer.java"
    click ProductController "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/controller/ProductController.java"
    click ProductService "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/service/ProductService.java"
    click ProductRepository "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/repository/ProductRepository.java"
    click ProductEntity "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/model/Product.java"
    click ProductRequest "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/dto/ProductRequest.java"
    click ApiError "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/dto/ApiErrorResponse.java"
    click GlobalHandler "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/exception/GlobalExceptionHandler.java"
    click BizEx "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/exception/BusinessException.java"
    click DupEx "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/exception/DuplicateResourceException.java"
    click NotFoundEx "https://github.com/josamvkd/global-exception-handling/blob/main/src/main/java/com/josamtechie/api/exception/ResourceNotFoundException.java"
    click Tests "https://github.com/josamvkd/global-exception-handling/blob/main/src/test/java/com/josamtechie/api/GlobalExceptionHandlingApplicationTests.java"

    %% =========================================================
    %% Styles (color is critical)
    %% =========================================================
    classDef external fill:#ffffff,stroke:#334155,stroke-width:1px,color:#0f172a
    classDef infra fill:#e2e8f0,stroke:#475569,stroke-width:1px,color:#0f172a
    classDef web fill:#dbeafe,stroke:#2563eb,stroke-width:1px,color:#0f172a
    classDef service fill:#dcfce7,stroke:#16a34a,stroke-width:1px,color:#052e16
    classDef repo fill:#f3e8ff,stroke:#7c3aed,stroke-width:1px,color:#2e1065
    classDef db fill:#f1f5f9,stroke:#0f172a,stroke-width:1px,color:#0f172a
    classDef dto fill:#ffedd5,stroke:#ea580c,stroke-width:1px,color:#7c2d12
    classDef model fill:#fae8ff,stroke:#a21caf,stroke-width:1px,color:#3b0764
    classDef exception fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef test fill:#fef9c3,stroke:#ca8a04,stroke-width:1px,color:#713f12

    %% Make exception links visually distinct
    linkStyle default stroke:#334155,stroke-width:1.2px
```
