You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.6 KiB
Go

package errors
import "fmt"
// nnet错误类型
var (
// ErrServerNotStarted 服务器未启动
ErrServerNotStarted = New("server not started")
// ErrServerAlreadyStarted 服务器已启动
ErrServerAlreadyStarted = New("server already started")
// ErrConnectionNotFound 连接未找到
ErrConnectionNotFound = New("connection not found")
// ErrRouteNotFound 路由未找到
ErrRouteNotFound = New("route not found")
// ErrHandlerNotFound 处理器未找到
ErrHandlerNotFound = New("handler not found")
// ErrProtocolNotSupported 协议不支持
ErrProtocolNotSupported = New("protocol not supported")
// ErrInvalidConfig 配置无效
ErrInvalidConfig = New("invalid config")
)
// Error nnet错误
type Error struct {
Message string
Code string
Cause error
}
// New 创建新错误
func New(message string) *Error {
return &Error{
Message: message,
}
}
// Newf 创建格式化错误
func Newf(format string, args ...interface{}) *Error {
return &Error{
Message: fmt.Sprintf(format, args...),
}
}
// WithCode 设置错误码
func (e *Error) WithCode(code string) *Error {
e.Code = code
return e
}
// WithCause 设置原因
func (e *Error) WithCause(cause error) *Error {
e.Cause = cause
return e
}
// Error 实现error接口
func (e *Error) Error() string {
if e.Cause != nil {
return fmt.Sprintf("%s: %v", e.Message, e.Cause)
}
return e.Message
}
// Unwrap 实现errors.Unwrap
func (e *Error) Unwrap() error {
return e.Cause
}
// Is 检查错误类型
func (e *Error) Is(target error) bool {
if t, ok := target.(*Error); ok {
return e.Code != "" && e.Code == t.Code
}
return false
}