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 }