1
0
Files
nex/backend/pkg/errors/errors.go
lanyuanxiaoyao f18904af1e feat: 实现分层架构,包含 domain、service、repository 和 pkg 层
- 新增 domain 层:model、provider、route、stats 实体
- 新增 service 层:models、providers、routing、stats 业务逻辑
- 新增 repository 层:models、providers、stats 数据访问
- 新增 pkg 工具包:errors、logger、validator
- 新增中间件:CORS、logging、recovery、request ID
- 新增数据库迁移:初始 schema 和索引
- 新增单元测试和集成测试
- 新增规范文档:config-management、database-migration、error-handling、layered-architecture、middleware-system、request-validation、structured-logging、test-coverage
- 移除 config 子包和 model_router(已迁移至分层架构)
2026-04-16 00:47:20 +08:00

75 lines
2.1 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
}
// 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)
)
// 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
}