package common import ( "code.hoteas.com/golang/hotime/log" "sync" ) // Error 框架基础错误类型 —— 线程安全的 error 封装。 // 通过组合(嵌入)方式在 Obj、DBError 等结构体中使用,提供统一的错误 API。 // 也用于 ObjToXxx / Map.GetXxx 等工具函数的可选错误报告参数。 // 设置 Logger 后,SetError 会自动将非 nil 错误写入日志。 type Error struct { error mu sync.RWMutex Logger *log.Logger } // Error 安全实现 error 接口 —— 内部 error 为 nil 时返回 "" 而非 panic func (that *Error) Error() string { that.mu.RLock() defer that.mu.RUnlock() if that.error == nil { return "" } return that.error.Error() } // HasError 快捷判断是否存在错误 func (that *Error) HasError() bool { that.mu.RLock() defer that.mu.RUnlock() return that.error != nil } // Unwrap 支持 errors.Is / errors.As 标准错误链 func (that *Error) Unwrap() error { that.mu.RLock() defer that.mu.RUnlock() return that.error } // GetError 获取内部 error(nil 表示无错误) func (that *Error) GetError() error { that.mu.RLock() defer that.mu.RUnlock() return that.error } // SetError 设置内部 error(传 nil 清除错误) // 当 Logger 已设置且 err 非 nil 时,自动写入 ERROR 级别日志 func (that *Error) SetError(err error) { that.mu.Lock() that.error = err logger := that.Logger that.mu.Unlock() if err != nil && logger != nil { logger.Error().Err(err).Msg("") } }