Skip to content

Commit 4e10c08

Browse files
committed
refactor: refactor error code definitions
- Consolidate error code definitions into error_code.go - Optimize error code structure with functional categorization - Improve error code documentation and comments
1 parent 08a2bb6 commit 4e10c08

File tree

11 files changed

+561
-431
lines changed

11 files changed

+561
-431
lines changed

README.md

+47-92
Original file line numberDiff line numberDiff line change
@@ -383,110 +383,65 @@ The project has recently undergone the following improvements:
383383
### 3. Eliminated Global Variables
384384
- **Problem**: The project used global variables to store service instances, violating dependency injection principles
385385
- **Solution**:
386-
- Removed the use of global variables `service.ExampleSvc` and `service.EventBus`
387-
- Passed service instances through dependency injection
388-
- Initialized services using dependency injection when starting the HTTP server
386+
- Removed global service variables
387+
- Properly injected services via the Factory pattern
388+
- Improved testability by making dependencies explicit
389389

390-
### 4. Improved Application Layer Integration
391-
- **Problem**: Application layer use cases were not fully utilized, with the HTTP server not enabling the application layer by default
390+
### 4. Enhanced Architecture Validation
391+
- **Problem**: Architecture validation was manual and prone to errors
392392
- **Solution**:
393-
- Enabled application layer use cases by default
394-
- Used the use case factory to create and manage use cases
395-
- Implemented clearer error handling and response mapping
393+
- Implemented automated layer dependency checking
394+
- Enforced strict architectural boundaries through code scanning
395+
- Added validation to CI pipeline
396396

397-
## Recent Optimizations
398-
399-
The project has recently undergone the following optimizations:
400-
401-
1. **Environment Variable Support**:
402-
- Added functionality for environment variable overrides for configuration files, making the application more flexible in containerized deployments
403-
- Used a unified prefix (APP_) and hierarchical structure (e.g., APP_MYSQL_HOST) to organize environment variables
404-
405-
2. **Unified Error Handling**:
406-
- Implemented an application-level error type system, supporting different types of errors (validation, not found, unauthorized, etc.)
407-
- Added unified error response handling, mapping internal errors to appropriate HTTP status codes
408-
- Improved error logging to ensure all unexpected errors are properly recorded
397+
### 5. Graceful Shutdown
398+
- **Problem**: Application didn't handle shutdown gracefully, potentially causing data loss
399+
- **Solution**:
400+
- Implemented a graceful shutdown mechanism for the server, ensuring all in-flight requests are completed before shutting down
401+
- Added shutdown timeout settings to prevent the shutdown process from hanging indefinitely
402+
- Improved signal handling, supporting SIGINT and SIGTERM signals
409403

410-
3. **Request Logging Middleware**:
411-
- Added detailed request logging middleware to record request methods, paths, status codes, latency, and other information
412-
- In debug mode, request and response bodies can be logged to help developers troubleshoot issues
413-
- Intelligently identifies content types to avoid logging binary content
404+
### 6. Internationalization Support
405+
- **Problem**: The application lacked proper internationalization support
406+
- **Solution**:
407+
- Added translation middleware for multi-language validation error messages
408+
- Automatically selected appropriate language based on the Accept-Language header
414409

415-
4. **Request ID Tracking**:
416-
- Generated unique request IDs for each request, facilitating tracking in distributed systems
417-
- Returned request IDs in response headers for client reference
418-
- Included request IDs in logs to correlate multiple log entries for the same request
410+
### 7. CORS Support
411+
- **Problem**: Cross-origin requests were not properly handled
412+
- **Solution**:
413+
- Added CORS middleware to handle cross-origin requests
414+
- Configured allowed origins, methods, headers, and credentials
419415

420-
5. **Graceful Shutdown**:
421-
- Implemented a graceful shutdown mechanism for the server, ensuring all in-flight requests are completed before shutting down
422-
- Added shutdown timeout settings to prevent the shutdown process from hanging indefinitely
423-
- Improved signal handling, supporting SIGINT and SIGTERM signals
416+
### 8. Debugging Tools
417+
- **Problem**: Diagnosis of performance issues in production was difficult
418+
- **Solution**:
419+
- Integrated pprof performance analysis tools for diagnosing performance issues in production environments
420+
- Can be enabled or disabled via configuration file
424421

425-
6. **Internationalization Support**:
426-
- Added translation middleware for multi-language validation error messages
427-
- Automatically selected appropriate language based on the Accept-Language header
422+
### 9. Advanced Redis Integration
423+
- **Problem**: Redis implementation was limited and lacked proper connection management
424+
- **Solution**:
425+
- Enhanced Redis client with proper connection pooling
426+
- Added comprehensive health checks and monitoring
427+
- Improved error handling and connection lifecycle management
428428

429-
7. **CORS Support**:
430-
- Added CORS middleware to handle cross-origin requests
431-
- Configured allowed origins, methods, headers, and credentials
429+
### 10. Structured Request Logging
430+
- **Problem**: API requests lacked proper logging, making debugging difficult
431+
- **Solution**:
432+
- Implemented comprehensive request logging middleware
433+
- Added request ID tracking for correlating logs
434+
- Configured log levels based on status codes
432435

433-
8. **Debugging Tools**:
434-
- Integrated pprof performance analysis tools for diagnosing performance issues in production environments
435-
- Can be enabled or disabled via configuration file
436+
### 11. Unified Error Response Format
437+
- **Problem**: Error responses had inconsistent formats across the API
438+
- **Solution**:
439+
- Standardized error response structure with code, message, and details
440+
- Added documentation references to errors
441+
- Implemented consistent HTTP status code mapping
436442

437443
These optimizations make the project more robust, maintainable, and provide a better development experience.
438444

439-
## Usage Guide
440-
441-
### Environment Preparation
442-
443-
Start MySQL using Docker:
444-
```bash
445-
docker run --name mysql-local \
446-
-e MYSQL_ROOT_PASSWORD=mysqlroot \
447-
-e MYSQL_DATABASE=go-hexagonal \
448-
-e MYSQL_USER=user \
449-
-e MYSQL_PASSWORD=mysqlroot \
450-
-p 3306:3306 \
451-
-d mysql:latest
452-
```
453-
454-
### Development Tool Installation
455-
456-
```bash
457-
# Install development tools
458-
make init && make precommit.rehook
459-
```
460-
461-
Or install manually:
462-
463-
```bash
464-
# Install pre-commit
465-
brew install pre-commit
466-
# Install golangci-lint
467-
brew install golangci-lint
468-
# Install commitlint
469-
npm install -g @commitlint/cli @commitlint/config-conventional
470-
# Add commitlint configuration
471-
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
472-
# Add pre-commit hook
473-
make precommit.rehook
474-
```
475-
476-
### Running the Project
477-
478-
```bash
479-
# Run the project
480-
go run cmd/main.go
481-
```
482-
483-
### Testing
484-
485-
```bash
486-
# Run tests
487-
go test ./...
488-
```
489-
490445
## Extension Plans
491446

492447
- **gRPC Support** - Add gRPC service implementation

README.zh.md

+53-98
Original file line numberDiff line numberDiff line change
@@ -362,131 +362,86 @@ logger.InfoContext(logCtx, "正在创建新实体",
362362
zap.String("entity_name", entity.Name))
363363
```
364364

365-
## 项目优化
365+
## 项目改进
366366

367-
本项目最近经过以下优化
367+
本项目最近进行了以下改进
368368

369369
### 1. 统一API版本
370-
- **问题**项目同时存在v1和v2 API版本,导致代码重复和维护困难
370+
- **问题**项目同时存在v1和v2两个API版本,导致代码重复和维护困难
371371
- **解决方案**
372-
- 统一API路由,将所有API放在`/api`路径下
372+
- 统一API路由,所有API都放在`/api`路径下
373373
- 保留`/v2`路径以向后兼容
374-
- 使用应用层用例处理所有请求,逐步淘汰直接调用领域服务
374+
- 使用应用层用例处理所有请求,逐步淘汰直接的领域服务调用
375375

376376
### 2. 增强依赖注入
377377
- **问题**:Wire依赖注入配置存在重复绑定问题,导致生成失败
378378
- **解决方案**
379379
- 重构`wire.go`文件,移除重复绑定定义
380-
- 使用provider函数替代直接绑定
380+
- 使用提供者函数代替直接绑定
381381
- 添加事件处理器注册逻辑
382382

383383
### 3. 消除全局变量
384384
- **问题**:项目使用全局变量存储服务实例,违反依赖注入原则
385385
- **解决方案**
386-
- 移除全局变量`service.ExampleSvc``service.EventBus`的使用
387-
- 通过依赖注入传递服务实例
388-
- 启动HTTP服务器时使用依赖注入初始化服务
386+
- 移除全局服务变量
387+
- 通过工厂模式正确注入服务
388+
- 通过显式依赖提高可测试性
389389

390-
### 4. 改进应用层集成
391-
- **问题**应用层用例未充分利用,HTTP服务器默认不启用应用层
390+
### 4. 增强架构验证
391+
- **问题**架构验证是手动且容易出错的
392392
- **解决方案**
393-
- 默认启用应用层用例
394-
- 使用用例工厂创建和管理用例
395-
- 实现更清晰的错误处理和响应映射
393+
- 实现自动化层依赖检查
394+
- 通过代码扫描强制严格的架构边界
395+
- 将验证添加到CI流程
396396

397-
## 最近的优化
398-
399-
本项目最近经过以下优化:
400-
401-
1. **环境变量支持**
402-
- 添加配置文件的环境变量覆盖功能,使应用在容器化部署中更灵活
403-
- 使用统一前缀(APP_)和层次结构(如APP_MYSQL_HOST)组织环境变量
404-
405-
2. **统一错误处理**
406-
- 实现应用级错误类型系统,支持不同类型的错误(验证错误、未找到、未授权等)
407-
- 添加统一错误响应处理,将内部错误映射到合适的HTTP状态码
408-
- 改进错误日志记录,确保所有意外错误被正确记录
397+
### 5. 优雅关闭
398+
- **问题**:应用程序没有优雅处理关闭过程,可能导致数据丢失
399+
- **解决方案**
400+
- 为服务器实现优雅关闭机制,确保所有运行中的请求在关闭前完成
401+
- 添加关闭超时设置,防止关闭过程无限期挂起
402+
- 改进信号处理,支持SIGINT和SIGTERM信号
409403

410-
3. **请求日志中间件**
411-
- 添加详细的请求日志中间件,记录请求方法、路径、状态码、延迟等信息
412-
- 在调试模式下,可以记录请求和响应体,帮助开发者排查问题
413-
- 智能识别内容类型,避免记录二进制内容
404+
### 6. 国际化支持
405+
- **问题**:应用程序缺乏适当的国际化支持
406+
- **解决方案**
407+
- 添加翻译中间件,支持多语言验证错误消息
408+
- 根据Accept-Language头自动选择适当的语言
414409

415-
4. **请求ID跟踪**
416-
- 为每个请求生成唯一的请求ID,便于在分布式系统中跟踪
417-
- 在响应头中返回请求ID,供客户端参考
418-
- 在日志中包含请求ID,关联同一请求的多个日志条目
410+
### 7. CORS支持
411+
- **问题**:跨源请求没有得到正确处理
412+
- **解决方案**
413+
- 添加CORS中间件处理跨源请求
414+
- 配置允许的来源、方法、头和凭据
419415

420-
5. **优雅关闭**
421-
- 实现服务器的优雅关闭机制,确保所有运行中的请求在关闭前完成
422-
- 添加关闭超时设置,防止关闭过程无限期挂起
423-
- 改进信号处理,支持SIGINT和SIGTERM信号
416+
### 8. 调试工具
417+
- **问题**:在生产环境中诊断性能问题很困难
418+
- **解决方案**
419+
- 集成pprof性能分析工具,用于诊断生产环境中的性能问题
420+
- 可以通过配置文件启用或禁用
424421

425-
6. **国际化支持**
426-
- 添加翻译中间件,支持多语言验证错误消息
427-
- 根据Accept-Language头自动选择适当的语言
422+
### 9. 高级Redis集成
423+
- **问题**:Redis实现有限,缺乏适当的连接管理
424+
- **解决方案**
425+
- 使用适当的连接池增强Redis客户端
426+
- 添加全面的健康检查和监控
427+
- 改进错误处理和连接生命周期管理
428428

429-
7. **CORS支持**
430-
- 添加CORS中间件,处理跨域请求
431-
- 配置允许的来源、方法、头和凭据
429+
### 10. 结构化请求日志
430+
- **问题**:API请求缺乏适当的日志记录,使调试变得困难
431+
- **解决方案**
432+
- 实现全面的请求日志中间件
433+
- 添加请求ID跟踪,用于关联日志
434+
- 根据状态码配置日志级别
432435

433-
8. **调试工具**
434-
- 集成pprof性能分析工具,用于诊断生产环境中的性能问题
435-
- 可通过配置文件启用或禁用
436+
### 11. 统一错误响应格式
437+
- **问题**:API中的错误响应格式不一致
438+
- **解决方案**
439+
- 标准化错误响应结构,包含代码、消息和详情
440+
- 为错误添加文档引用
441+
- 实现一致的HTTP状态码映射
436442

437443
这些优化使项目更加健壮、可维护,并提供更好的开发体验。
438444

439-
## 使用指南
440-
441-
### 环境准备
442-
443-
使用Docker启动MySQL:
444-
```bash
445-
docker run --name mysql-local \
446-
-e MYSQL_ROOT_PASSWORD=mysqlroot \
447-
-e MYSQL_DATABASE=go-hexagonal \
448-
-e MYSQL_USER=user \
449-
-e MYSQL_PASSWORD=mysqlroot \
450-
-p 3306:3306 \
451-
-d mysql:latest
452-
```
453-
454-
### 开发工具安装
455-
456-
```bash
457-
# 安装开发工具
458-
make init && make precommit.rehook
459-
```
460-
461-
或手动安装:
462-
463-
```bash
464-
# 安装pre-commit
465-
brew install pre-commit
466-
# 安装golangci-lint
467-
brew install golangci-lint
468-
# 安装commitlint
469-
npm install -g @commitlint/cli @commitlint/config-conventional
470-
# 添加commitlint配置
471-
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
472-
# 添加pre-commit钩子
473-
make precommit.rehook
474-
```
475-
476-
### 运行项目
477-
478-
```bash
479-
# 运行项目
480-
go run cmd/main.go
481-
```
482-
483-
### 测试
484-
485-
```bash
486-
# 运行测试
487-
go test ./...
488-
```
489-
490445
## 扩展计划
491446

492447
- **gRPC支持** - 添加gRPC服务实现

0 commit comments

Comments
 (0)