package cassandra import ( "errors" "fmt" ) // 定義統一的錯誤類型 var ( // ErrNotFound 表示記錄未找到 ErrNotFound = &Error{ Code: "NOT_FOUND", Message: "record not found", } // ErrAcquireLockFailed 表示獲取鎖失敗 ErrAcquireLockFailed = &Error{ Code: "LOCK_ACQUIRE_FAILED", Message: "acquire lock failed", } // ErrInvalidInput 表示輸入參數無效 ErrInvalidInput = &Error{ Code: "INVALID_INPUT", Message: "invalid input parameter", } // ErrNoPartitionKey 表示缺少 Partition Key ErrNoPartitionKey = &Error{ Code: "NO_PARTITION_KEY", Message: "no partition key defined in struct", } // ErrMissingTableName 表示缺少 TableName 方法 ErrMissingTableName = &Error{ Code: "MISSING_TABLE_NAME", Message: "struct must implement TableName() method", } // ErrNoFieldsToUpdate 表示沒有欄位需要更新 ErrNoFieldsToUpdate = &Error{ Code: "NO_FIELDS_TO_UPDATE", Message: "no fields to update", } // ErrMissingWhereCondition 表示缺少 WHERE 條件 ErrMissingWhereCondition = &Error{ Code: "MISSING_WHERE_CONDITION", Message: "operation requires at least one WHERE condition for safety", } // ErrMissingPartitionKey 表示 WHERE 條件中缺少 Partition Key ErrMissingPartitionKey = &Error{ Code: "MISSING_PARTITION_KEY", Message: "operation requires all partition keys in WHERE clause", } ) // Error 是統一的錯誤類型 type Error struct { Code string // 錯誤代碼 Message string // 錯誤訊息 Table string // 相關的表名(可選) Err error // 底層錯誤(可選) } // Error 實現 error 介面 func (e *Error) Error() string { if e.Table != "" { if e.Err != nil { return fmt.Sprintf("cassandra [%s] (table: %s): %s: %v", e.Code, e.Table, e.Message, e.Err) } return fmt.Sprintf("cassandra [%s] (table: %s): %s", e.Code, e.Table, e.Message) } if e.Err != nil { return fmt.Sprintf("cassandra [%s]: %s: %v", e.Code, e.Message, e.Err) } return fmt.Sprintf("cassandra [%s]: %s", e.Code, e.Message) } // Unwrap 返回底層錯誤 func (e *Error) Unwrap() error { return e.Err } // WithTable 為錯誤添加表名資訊 func (e *Error) WithTable(table string) *Error { return &Error{ Code: e.Code, Message: e.Message, Table: table, Err: e.Err, } } // WithError 為錯誤添加底層錯誤 func (e *Error) WithError(err error) *Error { return &Error{ Code: e.Code, Message: e.Message, Table: e.Table, Err: err, } } // NewError 創建新的錯誤 func NewError(code, message string) *Error { return &Error{ Code: code, Message: message, } } // IsNotFound 檢查錯誤是否為 NotFound func IsNotFound(err error) bool { return errors.Is(err, ErrNotFound) } // IsLockFailed 檢查錯誤是否為獲取鎖失敗 func IsLockFailed(err error) bool { return errors.Is(err, ErrAcquireLockFailed) }