github.com/zhongdalu/gf@v1.0.0/g/errors/gerror/gerror.go (about) 1 // Copyright 2019 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 // Package errors provides simple functions to manipulate errors. 8 package gerror 9 10 import ( 11 "fmt" 12 13 "github.com/zhongdalu/gf/g/util/gconv" 14 ) 15 16 type ApiStack interface { 17 Stack() string 18 } 19 20 type ApiCause interface { 21 Cause() error 22 } 23 24 // New returns an error that formats as the given value. 25 func New(value interface{}) error { 26 if value == nil { 27 return nil 28 } 29 return NewText(gconv.String(value)) 30 } 31 32 // NewText returns an error that formats as the given text. 33 func NewText(text string) error { 34 if text == "" { 35 return nil 36 } 37 return &Error{ 38 stack: callers(), 39 text: text, 40 } 41 } 42 43 // Wrap wraps error with text. 44 // It returns nil if given err is nil. 45 func Wrap(err error, text string) error { 46 if err == nil { 47 return nil 48 } 49 return &Error{ 50 error: err, 51 stack: callers(), 52 text: text, 53 } 54 } 55 56 // Wrapf returns an error annotating err with a stack trace 57 // at the point Wrapf is called, and the format specifier. 58 // It returns nil if given err is nil. 59 func Wrapf(err error, format string, args ...interface{}) error { 60 if err == nil { 61 return nil 62 } 63 return &Error{ 64 error: err, 65 stack: callers(), 66 text: fmt.Sprintf(format, args...), 67 } 68 } 69 70 // Cause returns the root cause error. 71 func Cause(err error) error { 72 if err != nil { 73 if e, ok := err.(ApiCause); ok { 74 return e.Cause() 75 } 76 } 77 return err 78 } 79 80 // Stack returns the stack callers as string. 81 // It returns an empty string id the <err> does not support stacks. 82 func Stack(err error) string { 83 if err == nil { 84 return "" 85 } 86 if e, ok := err.(ApiStack); ok { 87 return e.Stack() 88 } 89 return "" 90 }