Files
hotime/common/error.go
T

60 lines
1.5 KiB
Go
Raw Normal View History

2021-05-24 07:27:41 +08:00
package common
2017-08-04 08:20:59 +00:00
2021-05-25 19:53:34 +08:00
import (
"code.hoteas.com/golang/hotime/log"
"sync"
2021-05-25 19:53:34 +08:00
)
// Error 框架基础错误类型 —— 线程安全的 error 封装。
// 通过组合(嵌入)方式在 Obj、DBError 等结构体中使用,提供统一的错误 API。
// 也用于 ObjToXxx / Map.GetXxx 等工具函数的可选错误报告参数。
// 设置 Logger 后,SetError 会自动将非 nil 错误写入日志。
2017-08-04 08:20:59 +00:00
type Error struct {
error
mu sync.RWMutex
Logger *log.Logger
2017-08-04 08:20:59 +00:00
}
// 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 获取内部 errornil 表示无错误)
2021-05-25 05:08:17 +08:00
func (that *Error) GetError() error {
that.mu.RLock()
defer that.mu.RUnlock()
2021-05-25 05:08:17 +08:00
return that.error
2017-08-04 08:20:59 +00:00
}
// SetError 设置内部 error(传 nil 清除错误)
// 当 Logger 已设置且 err 非 nil 时,自动写入 ERROR 级别日志
2021-05-25 05:08:17 +08:00
func (that *Error) SetError(err error) {
that.mu.Lock()
2021-05-25 05:08:17 +08:00
that.error = err
logger := that.Logger
that.mu.Unlock()
if err != nil && logger != nil {
logger.Error().Err(err).Msg("")
2021-05-25 19:53:34 +08:00
}
2017-08-04 08:20:59 +00:00
}