1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-02 09:17:55 -04:00
v2fly/common/errors/errors.go

109 lines
2.0 KiB
Go
Raw Normal View History

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