diff --git a/.gitignore b/.gitignore index f1c181e..6227e56 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,6 @@ # Output of the go coverage tool, specifically when used with LiteIDE *.out + +# idea +.idea \ No newline at end of file diff --git a/README.md b/README.md index a5f5a5b..54a54a6 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,65 @@ # errors -stack errors for golang +Stack errors for golang + +Package errors provides simple error handling primitives. + +`go get github.com/pharosnet/errors` + +The traditional error handling idiom in Go is roughly akin to +```go +if err != nil { + return err +} +``` +which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. + +## Adding context to an error + +The errors.Wrap function returns a new error that adds context to the original error. For example +```go +_, err := ioutil.ReadAll(r) +if err != nil { + return errors.Wrap(err) +} +``` +## Retrieving the cause of an error + +Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. +```go +type Errors interface { + Error() string + Cause() error + OccurTime() time.Time + PCS() []uintptr + Contains(error) bool + Format(fmt.State, rune) +} +``` +`errors.Contains` will search target in error which implements `Errors`, For example: +```go + e1 := io.EOF + e2 := errors.With(e1, "error2") + e3 := errors.WithF(e2, "%s", "error3") + + if errors.Contains(e3, e2) { + // TODO .. + } + + if errors.Contains(e3, e1) { + // TODO ... + } +``` + +[Read the examples for more usages.](https://github.com/pharosnet/errors/tree/master/example) + +[Read the package documentation for more information](https://godoc.org/github.com/pharosnet/errors). + +## Contributing + +We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. + +Before proposing a change, please discuss your change by raising an issue. + +## License + +GNU GENERAL PUBLIC LICENSE(v3) \ No newline at end of file diff --git a/config.go b/config.go new file mode 100644 index 0000000..3b47ecb --- /dev/null +++ b/config.go @@ -0,0 +1,52 @@ +package errors + +import ( + "fmt" + "sync" + "time" +) + +var _cfg *config +var _once = new(sync.Once) + +func init() { + _once.Do(func() { + _cfg = &config{loc: time.Local, depth: 1, skip: 3, formatFn: DefaultFormatFn} + }) +} + +type config struct { + loc *time.Location + depth int + skip int + formatFn Format +} + +func (c *config) SetTimeLocation(loc *time.Location) { + if loc == nil { + panic("errors set time location failed, loc is nil") + } + c.loc = loc +} + +func (c *config) SetStack(depth int, skip int) { + if depth < 1 { + panic(fmt.Errorf("errors set stack failed, depth valued %d is invalid", depth)) + } + if skip < 1 { + panic(fmt.Errorf("errors set stack failed, skip valued %d is invalid", skip)) + } + c.depth = depth + c.skip = skip +} + +func (c *config) SetFormatFunc(fn Format) { + if fn == nil { + panic("errors set format func failed") + } + c.formatFn = fn +} + +func Configure() *config { + return _cfg +} diff --git a/env.go b/env.go new file mode 100644 index 0000000..d944dd8 --- /dev/null +++ b/env.go @@ -0,0 +1,43 @@ +package errors + +import ( + "os" + "strings" +) + +func goEnv() []string { + env := make([]string, 0, 2) + // goroot + goroot := os.Getenv("GOROOT") + if len(goroot) > 0 { + if strings.Contains(goroot, `\`) && strings.Contains(goroot, ":") { // win + goroot = strings.Replace(goroot, `\`, "/", -1) + } + env = append(env, goroot) + } + gopath := os.Getenv("GOPATH") + if len(gopath) == 0 { + return env + } + if strings.Contains(gopath, `\`) && strings.Contains(gopath, ":") { // win + gopath = strings.Replace(gopath, `\`, "/", -1) + if strings.Contains(gopath, ";") { + gopaths := strings.Split(gopath, ";") + for _, item := range gopaths { + env = append(env, strings.TrimSpace(item)) + } + } else { + env = append(env, strings.TrimSpace(gopath)) + } + } else { // unix + if strings.Contains(gopath, ":") { + gopaths := strings.Split(gopath, ":") + for _, item := range gopaths { + env = append(env, strings.TrimSpace(item)) + } + } else { + env = append(env, strings.TrimSpace(gopath)) + } + } + return env +} diff --git a/errors.go b/errors.go new file mode 100644 index 0000000..29874b5 --- /dev/null +++ b/errors.go @@ -0,0 +1,134 @@ +package errors + +import ( + "fmt" + "time" +) + +func New(message string) error { + return &errorUp{ + msg: message, + cause: nil, + pcs: callers(), + occurred: timeNow(), + } +} + +func ErrorF(format string, args ...interface{}) error { + return &errorUp{ + msg: fmt.Sprintf(format, args...), + cause: nil, + pcs: callers(), + occurred: timeNow(), + } +} + +func With(cause error, message string) error { + if cause == nil { + return nil + } + return &errorUp{ + msg: message, + cause: cause, + pcs: callers(), + occurred: timeNow(), + } +} + +func WithF(cause error, format string, args ...interface{}) error { + if cause == nil { + return nil + } + return &errorUp{ + msg: fmt.Sprintf(format, args...), + cause: cause, + pcs: callers(), + occurred: timeNow(), + } +} + +func Wrap(e error) error { + return &errorUp{ + msg: e.Error(), + cause: nil, + pcs: callers(), + occurred: timeNow(), + } +} + +func NewByAssigned(depth int, skip int, message string) error { + return &errorUp{ + msg: message, + cause: nil, + pcs: callersByAssigned(depth, skip), + occurred: timeNow(), + } +} + +type errorUp struct { + msg string + cause error + pcs []uintptr + occurred time.Time +} + +func (e *errorUp) Error() string { + return e.msg +} + +func (e *errorUp) OccurTime() time.Time { + return e.occurred +} + +func (e *errorUp) PCS() []uintptr { + return e.pcs +} + +func (e *errorUp) Format(s fmt.State, verb rune) { + Configure().formatFn(s, verb, e) +} + +func (e *errorUp) Cause() error { + if e.cause != nil { + return e.cause + } + return nil +} + +func (e *errorUp) Contains(cause error) bool { + if e.cause == nil { + return false + } + err := e.cause + if err != nil { + if err == cause { + return true + } + hasCause, ok := err.(Errors) + if !ok { + return false + } + return hasCause.Contains(cause) + } + return false +} + +func Contains(a error, b error) bool { + if a == nil || b == nil { + return false + } + e, ok := a.(Errors) + if !ok { + return false + } + return e.Contains(b) +} + +type Errors interface { + Error() string + Cause() error + OccurTime() time.Time + PCS() []uintptr + Contains(error) bool + Format(fmt.State, rune) +} diff --git a/example/contains.go b/example/contains.go new file mode 100644 index 0000000..de3d541 --- /dev/null +++ b/example/contains.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "github.com/pharosnet/errors" + "io" +) + +func main() { + e1 := io.EOF + e2 := errors.With(e1, "error2") + e3 := errors.WithF(e2, "%s", "error3") + + if errors.Contains(e3, e2) { + // TODO .. + } + + if errors.Contains(e3, e1) { + // TODO ... + } + + fmt.Println(errors.Contains(e3, e2)) + fmt.Println(errors.Contains(e3, e1)) + +} diff --git a/example/json.go b/example/json.go new file mode 100644 index 0000000..6d7e3bf --- /dev/null +++ b/example/json.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + "github.com/pharosnet/errors" + "io" +) + +func main() { + errors.Configure().SetFormatFunc(errors.JsonFormatFn) + e1 := io.EOF + e2 := errors.With(e1, "error 2") + fmt.Printf("%+v", e2) + + // output: + // + // { + // "msg": "error 2", + // "occurTime": "2018-08-20 08:23:01.3592428 +0800 CST", + // "stack": [ + // { + // "fn": "main.main", + // "home": "E:/golang/workspace", + // "file": "github.com/pharosnet/errors/example/json.go", + // "line": 12 + // } + // ], + // "cause": { + // "msg": "EOF" + // } + // } +} diff --git a/example/new.go b/example/new.go new file mode 100644 index 0000000..4053431 --- /dev/null +++ b/example/new.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "github.com/pharosnet/errors" +) + +func main() { + e := errors.New("some error") + fmt.Println(e) + e = errors.ErrorF("%s", "2") + fmt.Println(e) + e = errors.NewByAssigned(32, 3, "new by assigned") + fmt.Printf("%+v\n", e) +} diff --git a/example/stack.go b/example/stack.go new file mode 100644 index 0000000..8c71087 --- /dev/null +++ b/example/stack.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "github.com/pharosnet/errors" +) + +func main() { + e1 := errors.New("error 1") + e2 := errors.With(e1, "error 2") + fmt.Println(e2) + // output + // + // error 2 + fmt.Println("======================") + fmt.Printf("%+v", e2) + // output + // + // error 2 + // [T] 2018-08-20 07:29:07.2631465 +0800 CST + // [F] main.main + // [P] E:/golang/workspace + // [X] github.com/pharosnet/errors/example/stack.go:10 + // error 1 + // [T] 2018-08-20 07:29:07.2631465 +0800 CST + // [F] main.main + // [P] E:/golang/workspace + // [X] github.com/pharosnet/errors/example/stack.go:9 + +} diff --git a/example/wrap.go b/example/wrap.go new file mode 100644 index 0000000..44b11ed --- /dev/null +++ b/example/wrap.go @@ -0,0 +1,12 @@ +package main + +import ( + "fmt" + "github.com/pharosnet/errors" + "io" +) + +func main() { + e := errors.Wrap(io.EOF) + fmt.Printf("%+v\n", e) +} diff --git a/format.go b/format.go new file mode 100644 index 0000000..3bf1ff5 --- /dev/null +++ b/format.go @@ -0,0 +1,81 @@ +package errors + +import ( + "fmt" + "io" + "runtime" +) + +type Format func(s fmt.State, verb rune, e Errors) + +func DefaultFormatFn(s fmt.State, verb rune, e Errors) { + switch verb { + case 'v': + switch { + case s.Flag('+'): + fmt.Fprintf(s, "%s\n", e.Error()) + for i, pc := range e.PCS() { + fn := runtime.FuncForPC(pc) + if fn == nil { + io.WriteString(s, "unknown") + } else { + file, line := fn.FileLine(pc) + home, filename := fileName(file) + if i == 0 { + fmt.Fprintf(s, "\t[T] %s\n\t[F] %s\n\t[H] %s\n\t[F] %s:%d \n", e.OccurTime().String(), fn.Name(), home, filename, line) + } else { + fmt.Fprintf(s, "\t[F] %s\n\t[H] %s\n\t[F] %s:%d \n", fn.Name(), home, filename, line) + } + } + } + if e.Cause() != nil { + hasCause, ok := e.Cause().(Errors) + if !ok { + fmt.Fprintf(s, "%v\n", e.Cause()) + } else { + hasCause.Format(s, verb) + } + } + default: + fmt.Fprintf(s, "%s", e.Error()) + } + } +} + +func JsonFormatFn(s fmt.State, verb rune, e Errors) { + switch verb { + case 'v': + switch { + case s.Flag('+'): + io.WriteString(s, "{") + fmt.Fprintf(s, `"msg":"%s", "occurTime":"%s", "stack":[`, e.Error(), e.OccurTime()) + for i, pc := range e.PCS() { + if i > 0 { + io.WriteString(s, ",") + } + fn := runtime.FuncForPC(pc) + if fn == nil { + fmt.Fprintf(s, `{"fn":"%s", "home":"%s", "file":"%s", "line":%d}`, "unknown", "unknown", "unknown", 0) + } else { + file, line := fn.FileLine(pc) + home, filename := fileName(file) + fmt.Fprintf(s, `{"fn":"%s", "home":"%s", "file":"%s", "line":%d}`, fn.Name(), home, filename, line) + } + } + io.WriteString(s, "]") + if e.Cause() != nil { + io.WriteString(s, ",") + hasCause, ok := e.Cause().(Errors) + if !ok { + fmt.Fprintf(s, `"cause":{"msg":"%s"}`, e.Cause().Error()) + } else { + io.WriteString(s, `"cause":`) + hasCause.Format(s, verb) + } + } + io.WriteString(s, "}") + default: + fmt.Fprintf(s, "%s", e.Error()) + } + } +} diff --git a/stack.go b/stack.go new file mode 100644 index 0000000..b664f11 --- /dev/null +++ b/stack.go @@ -0,0 +1,40 @@ +package errors + +import ( + "path" + "runtime" + "strings" + "time" +) + +func fileName(src string) (goPath string, file string) { + file = src + goHomes := goEnv() + if goHomes == nil { + return + } + for _, goHome := range goHomes { + if strings.Contains(file, goHome) { + goPath = goHome + file = strings.Replace(file, path.Join(goHome, "src"), "", 1)[1:] + return + } + } + return +} + +func timeNow() time.Time { + return time.Now().In(_cfg.loc) +} + +func callers() []uintptr { + pcs := make([]uintptr, Configure().depth) + n := runtime.Callers(Configure().skip, pcs[:]) + return pcs[0:n] +} + +func callersByAssigned(depth int, skip int) []uintptr { + pcs := make([]uintptr, depth) + n := runtime.Callers(skip, pcs[:]) + return pcs[0:n] +}