1
0
Files
nex/backend/pkg/errors/errors.go
lanyuanxiaoyao d92db73937 refactor: 后端代码质量优化 - 复用公共库、使用标准库、类型安全错误判断
## 高优先级修复
- stats_service_impl: 使用 strings.SplitN 替代错误的索引分割
- provider_handler: 使用 errors.Is(err, gorm.ErrDuplicatedKey) 替代字符串匹配
- client: 重写 isNetworkError 使用 errors.As/Is 类型安全判断
- proxy_handler: 使用 encoding/json 标准库解析 JSON(extractModelName、isStreamRequest)

## 中优先级修复
- stats_handler: 添加 parseDateParam 辅助函数消除重复日期解析
- pkg/errors: 新增 ErrRequestCreate/Send/ResponseRead 错误类型和 WithCause 方法
- client: 使用结构化错误替代 fmt.Errorf
- ConversionEngine: logger 依赖注入,替换所有 zap.L() 调用

## 低优先级修复
- encoder: 删除 joinStrings,使用 strings.Join
- adapter: 删除 modelInfoRegex 正则,使用 isModelInfoPath 字符串函数

## 文档更新
- README.md: 添加公共库使用指南和编码规范章节
- specs: 同步 delta specs 到 main specs(error-handling、structured-logging、request-validation)

## 归档
- openspec/changes/archive/2026-04-20-refactor-backend-code-quality/
2026-04-20 16:42:48 +08:00

89 lines
2.6 KiB
Go

package errors
import (
"fmt"
"net/http"
)
// AppError 结构化应用错误
type AppError struct {
Code string `json:"code"`
Message string `json:"message"`
HTTPStatus int `json:"-"`
Cause error `json:"-"`
Context map[string]interface{} `json:"-"`
}
// Error implements error interface
func (e *AppError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("%s: %s (%v)", e.Code, e.Message, e.Cause)
}
return fmt.Sprintf("%s: %s", e.Code, e.Message)
}
// Unwrap returns the underlying error
func (e *AppError) Unwrap() error {
return e.Cause
}
// WithCause returns a copy of the error with the given cause
func (e *AppError) WithCause(cause error) *AppError {
return &AppError{
Code: e.Code,
Message: e.Message,
HTTPStatus: e.HTTPStatus,
Cause: cause,
Context: e.Context,
}
}
// NewAppError creates a new AppError
func NewAppError(code, message string, httpStatus int) *AppError {
return &AppError{
Code: code,
Message: message,
HTTPStatus: httpStatus,
}
}
// Predefined errors
var (
ErrModelNotFound = NewAppError("model_not_found", "模型未找到", http.StatusNotFound)
ErrModelDisabled = NewAppError("model_disabled", "模型已禁用", http.StatusNotFound)
ErrProviderNotFound = NewAppError("provider_not_found", "供应商未找到", http.StatusNotFound)
ErrProviderDisabled = NewAppError("provider_disabled", "供应商已禁用", http.StatusNotFound)
ErrInvalidRequest = NewAppError("invalid_request", "无效的请求", http.StatusBadRequest)
ErrInternal = NewAppError("internal_error", "内部错误", http.StatusInternalServerError)
ErrDatabaseNotInit = NewAppError("database_not_initialized", "数据库未初始化", http.StatusInternalServerError)
ErrConflict = NewAppError("conflict", "资源已存在", http.StatusConflict)
ErrRequestCreate = NewAppError("request_create_error", "创建请求失败", http.StatusInternalServerError)
ErrRequestSend = NewAppError("request_send_error", "发送请求失败", http.StatusBadGateway)
ErrResponseRead = NewAppError("response_read_error", "读取响应失败", http.StatusBadGateway)
)
// AsAppError 尝试将 error 转换为 *AppError
func AsAppError(err error) (*AppError, bool) {
if err == nil {
return nil, false
}
var appErr *AppError
if ok := is(err, &appErr); ok {
return appErr, true
}
return nil, false
}
func is(err error, target interface{}) bool {
// 简单的类型断言
if e, ok := err.(*AppError); ok {
// 直接赋值
switch t := target.(type) {
case **AppError:
*t = e
return true
}
}
return false
}