82 lines
2.1 KiB
Go
82 lines
2.1 KiB
Go
package errors
|
|
|
|
import "fmt"
|
|
|
|
// ErrorCode 错误码
|
|
type ErrorCode int
|
|
|
|
const (
|
|
ErrOK ErrorCode = iota
|
|
ErrInternalError
|
|
ErrCollectionNotFound
|
|
ErrDocumentNotFound
|
|
ErrInvalidRequest
|
|
ErrDuplicateKey
|
|
ErrDatabaseError
|
|
ErrQueryParseError
|
|
ErrAggregationError
|
|
)
|
|
|
|
// GomogError Gomog 错误类型
|
|
type GomogError struct {
|
|
Code ErrorCode `json:"code"`
|
|
Message string `json:"message"`
|
|
Err error `json:"-"`
|
|
}
|
|
|
|
func (e *GomogError) Error() string {
|
|
if e.Err != nil {
|
|
return fmt.Sprintf("[%d] %s: %v", e.Code, e.Message, e.Err)
|
|
}
|
|
return fmt.Sprintf("[%d] %s", e.Code, e.Message)
|
|
}
|
|
|
|
func (e *GomogError) Unwrap() error {
|
|
return e.Err
|
|
}
|
|
|
|
// 预定义错误
|
|
var (
|
|
ErrInternal = &GomogError{Code: ErrInternalError, Message: "internal error"}
|
|
ErrCollectionNotFnd = &GomogError{Code: ErrCollectionNotFound, Message: "collection not found"}
|
|
ErrDocumentNotFnd = &GomogError{Code: ErrDocumentNotFound, Message: "document not found"}
|
|
ErrInvalidReq = &GomogError{Code: ErrInvalidRequest, Message: "invalid request"}
|
|
ErrDuplicate = &GomogError{Code: ErrDuplicateKey, Message: "duplicate key"}
|
|
ErrDatabase = &GomogError{Code: ErrDatabaseError, Message: "database error"}
|
|
ErrQueryParse = &GomogError{Code: ErrQueryParseError, Message: "query parse error"}
|
|
ErrAggregation = &GomogError{Code: ErrAggregationError, Message: "aggregation error"}
|
|
)
|
|
|
|
// New 创建新错误
|
|
func New(code ErrorCode, message string) *GomogError {
|
|
return &GomogError{
|
|
Code: code,
|
|
Message: message,
|
|
}
|
|
}
|
|
|
|
// Wrap 包装错误
|
|
func Wrap(err error, code ErrorCode, message string) *GomogError {
|
|
return &GomogError{
|
|
Code: code,
|
|
Message: message,
|
|
Err: err,
|
|
}
|
|
}
|
|
|
|
// IsCollectionNotFound 判断是否是集合不存在错误
|
|
func IsCollectionNotFound(err error) bool {
|
|
if e, ok := err.(*GomogError); ok {
|
|
return e.Code == ErrCollectionNotFound
|
|
}
|
|
return false
|
|
}
|
|
|
|
// IsDocumentNotFound 判断是否是文档不存在错误
|
|
func IsDocumentNotFound(err error) bool {
|
|
if e, ok := err.(*GomogError); ok {
|
|
return e.Code == ErrDocumentNotFound
|
|
}
|
|
return false
|
|
}
|