API Types & Error Handling
Table of Contents
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendices
Introduction
This document describes the API types and error handling framework used across the system. It covers standardized request/response structures, pagination models, error code definitions, and middleware integration for request validation, response formatting, and error propagation. It also explains content-type handling, CORS configuration, middleware chain execution, API versioning considerations, backward compatibility, and client integration patterns.
Project Structure
The API types and error handling framework resides in the bi-common module under apitypes. It includes:
- Core types for requests, responses, pagination, and generic result wrappers
- Error construction and extraction utilities
- A comprehensive set of business error codes
- Middleware for response encoding, error encoding, content-type enforcement, CORS, and request ID injection
Diagram sources
- [response.go]
- [error.go]
- [request.go]
- [page.go]
- [result.go]
- [codes.go]
- [common.go]
- [encoder.go]
- [content_type.go]
- [cors.go]
- [http.go]
Section sources
Core Components
- Unified Response Model: Standardized JSON envelope with code, message, and optional data payload.
- Business Error Model: Wraps Kratos errors with a business error code embedded in metadata and mapped to HTTP status internally.
- Request Models: Common request DTOs for ID, batch IDs, time range, sort, and paginated queries.
- Pagination Model: Request validation, offset/limit calculation, and response wrapper.
- Generic Result Wrappers: Type-safe wrappers for lists, trees, options, IDs, and empty results.
- Error Codes: 7-digit code scheme (XXYYZZZ) with categories for client/server errors and module-specific allocations.
- Middleware: Response encoder, error encoder, JSON content-type enforcement, CORS, and request ID generation.
Section sources
- [response.go]
- [error.go]
- [request.go]
- [page.go]
- [result.go]
- [codes.go]
- [common.go]
- [encoder.go]
- [content_type.go]
- [cors.go]
- [http.go]
Architecture Overview
The API response pipeline integrates middleware to normalize all HTTP responses into a single JSON envelope while preserving Kratos error semantics. The error encoder extracts business codes and messages, falling back to inferred codes when necessary. The response encoder wraps successful payloads and supports list unwrapping for convenience.
Diagram sources
Detailed Component Analysis
Unified Response Model
- Structure: code, message, data (optional).
- Helpers: Success, SuccessWithMessage, Error, and constructors for page and generic results.
- Behavior: Responses are encoded as JSON with Content-Type application/json; charset=utf-8.
Diagram sources
Section sources
Business Error Model and Propagation
- Creation: NewBizError and NewBizErrorf attach a business code to a Kratos error and store it in metadata.
- Extraction: GetBizCode retrieves the business code; GetBizMessage retrieves the message.
- Status mapping: getHTTPStatus maps XX portion to HTTP status for internal Kratos handling; middleware ensures HTTP 200 with code/message.
Diagram sources
Section sources
Request and Pagination Models
- IDRequest and IDsRequest support single and batch identifiers with validation constraints.
- TimeRangeRequest validates chronological ordering.
- SortRequest normalizes sort direction to uppercase defaults.
- PageRequest enforces bounds and computes offset/limit; PageResponse wraps totals and lists.
Diagram sources
Section sources
Error Code Definitions and Categories
- Format: 7-digit code XXYYZZZ.
- XX groups: client errors (40–49) and server errors (50–59).
- YY groups: 00 for common, 01–99 for modules.
- ZZZ groups: 001–999 per category/module.
- Utilities: extract type/module/number, classify client/server/common, format and parse parts.
Diagram sources
Section sources
Middleware Integration
- ResponseEncoder: Wraps all responses into the unified envelope; supports list unwrapping when a single exported field named List exists.
- ErrorEncoder: Converts errors to unified format, inferring business codes from Kratos HTTP status when missing.
- JSONContentType: Ensures Content-Type header is application/json; compatible with hijacking and flushing.
- CORS: Configurable preflight handling, origin checks, credentials, exposed headers, and max age.
- RequestID: Generates and propagates a request identifier via context.
Diagram sources
Section sources
Dependency Analysis
- ResponseEncoder depends on Response helpers and reflection to unwrap list envelopes.
- ErrorEncoder depends on GetBizCode/GetBizMessage and inference from Kratos error codes.
- Error model depends on Kratos errors and stores business codes in metadata.
- CORS and JSON content-type middleware are independent filters suitable for HTTP servers.
Diagram sources
- [error.go]
- [response.go]
- [page.go]
- [request.go]
- [result.go]
- [common.go]
- [codes.go]
- [encoder.go]
- [content_type.go]
- [cors.go]
- [http.go]
Section sources
Performance Considerations
- ResponseEncoder uses reflection to detect list unwrapping; avoid deeply nested structures for large payloads to minimize reflection overhead.
- ErrorEncoder performs a single pass to extract business codes and infer fallbacks; keep error creation centralized to reduce branching.
- CORS preflight caching (Max-Age) reduces repeated preflight requests; tune MaxAge based on deployment needs.
- JSONContentType and ErrorEncoder set headers once; ensure no downstream middleware overrides content-type.
[No sources needed since this section provides general guidance]
Troubleshooting Guide
- Unexpected HTTP 5xx: Verify that business errors are constructed via NewBizError so they map to appropriate 4xx/5xx internally; the middleware returns HTTP 200 but sets code/message accordingly.
- Missing business code: Ensure errors are created with NewBizError or carry Kratos error with inferred mapping; otherwise, defaults to internal error.
- Incorrect Content-Type: Confirm JSONContentType middleware is applied before any write operations.
- CORS failures: Validate AllowOrigins, AllowCredentials, and exposed headers; ensure preflight OPTIONS is handled by CORS filter/handler.
- Pagination anomalies: Call Validate on PageRequest and use GetOffset/GetLimit consistently; enforce min/max page sizes at the boundary.
Section sources
Conclusion
The apitypes framework provides a cohesive, protocol-agnostic foundation for API responses and errors. By enforcing a single response envelope, a structured error code taxonomy, and robust middleware, it simplifies client integration, improves observability, and maintains backward compatibility. Projects should adopt the unified response and error patterns, define domain-specific error codes alongside common ones, and configure middleware consistently across services.
[No sources needed since this section summarizes without analyzing specific files]
Appendices
API Contracts and Examples
- Successful response envelope: see Response structure and Success helpers.
- Error response envelope: see Error helpers and ErrorEncoder behavior.
- Pagination contract: see PageRequest validation and PageResponse wrapping.
- List unwrapping: when returning a single exported field named List, the encoder flattens the response.
Section sources
Status Code Mappings
- Internal mapping: getHTTPStatus maps XX portions to HTTP status codes for Kratos errors.
- Client-facing: HTTP responses are returned with 200 OK; clients should inspect the code field to determine success.
Section sources
Content-Type and CORS Configuration
- Content-Type: JSONContentType ensures application/json; charset=utf-8 is set before writing.
- CORS: Configure AllowOrigins, AllowMethods, AllowHeaders, ExposeHeaders, AllowCredentials, and MaxAge; preflight OPTIONS is handled automatically.
Section sources
Middleware Chain Execution
- Typical order: RequestID → JSONContentType → CORS → Endpoint → ResponseEncoder/ErrorEncoder.
- Ensure JSONContentType and CORS are placed early to guarantee headers are set before writes.
Section sources
API Versioning and Backward Compatibility
- Version directories: Services commonly place API definitions under versioned namespaces (e.g., example/v1, anls/v1).
- Backward compatibility: Keep existing fields immutable; introduce new fields with defaults; maintain consistent response envelopes and error codes.
Section sources