v2ray-core/common/errors/errors.go

105 lines
1.9 KiB
Go
Raw Normal View History

2017-02-08 09:01:22 +00:00
// Package errors is a drop-in replacement for Golang lib 'errors'.
2016-12-04 08:10:47 +00:00
package errors
import (
"fmt"
2016-12-15 10:05:32 +00:00
2016-12-04 08:10:47 +00:00
"v2ray.com/core/common/serial"
)
2017-02-08 09:01:22 +00:00
type hasInnerError interface {
// Inner returns the underlying error of this one.
2016-12-04 08:10:47 +00:00
Inner() error
}
2017-02-21 22:14:07 +00:00
type actionRequired interface {
ActionRequired() bool
}
2017-02-08 09:01:22 +00:00
// Error is an error object with underlying error.
2016-12-04 08:10:47 +00:00
type Error struct {
2017-02-21 22:14:07 +00:00
message string
inner error
actionRequired bool
2016-12-04 08:10:47 +00:00
}
2017-02-08 09:01:22 +00:00
// Error implements error.Error().
func (v Error) Error() string {
2016-12-04 08:10:47 +00:00
return v.message
}
2017-02-08 09:01:22 +00:00
// Inner implements hasInnerError.Inner()
func (v Error) Inner() error {
2016-12-04 08:10:47 +00:00
if v.inner == nil {
return nil
}
return v.inner
}
func (v Error) ActionRequired() bool {
2017-02-21 22:14:07 +00:00
return v.actionRequired
}
func (v Error) RequireUserAction() Error {
v.actionRequired = true
return v
}
func (v Error) Message(msg ...interface{}) Error {
return Error{
inner: v,
message: serial.Concat(msg...),
}
}
func (v Error) Format(format string, values ...interface{}) Error {
return v.Message(fmt.Sprintf(format, values...))
}
2017-02-08 09:01:22 +00:00
// New returns a new error object with message formed from given arguments.
func New(msg ...interface{}) Error {
return Error{
2017-01-17 09:22:09 +00:00
message: serial.Concat(msg...),
2016-12-04 08:10:47 +00:00
}
}
// Base returns an Error based on the given error.
func Base(err error) Error {
return Error{
inner: err,
2016-12-04 08:10:47 +00:00
}
}
2016-12-15 10:05:32 +00:00
func Format(format string, values ...interface{}) error {
return New(fmt.Sprintf(format, values...))
}
// Cause returns the root cause of this error.
2016-12-04 08:10:47 +00:00
func Cause(err error) error {
if err == nil {
return nil
}
for {
2017-02-08 09:01:22 +00:00
inner, ok := err.(hasInnerError)
2017-02-21 22:14:07 +00:00
if !ok || inner.Inner() == nil {
2016-12-04 08:10:47 +00:00
break
}
2017-02-21 22:14:07 +00:00
err = inner.Inner()
}
return err
}
func IsActionRequired(err error) bool {
for err != nil {
if ar, ok := err.(actionRequired); ok && ar.ActionRequired() {
return true
}
inner, ok := err.(hasInnerError)
if !ok || inner.Inner() == nil {
2016-12-04 08:10:47 +00:00
break
}
err = inner.Inner()
}
2017-02-21 22:14:07 +00:00
return false
2016-12-04 08:10:47 +00:00
}