added README.md once again

This commit is contained in:
Timon Ringwald 2020-09-09 13:34:23 +02:00
parent 9d0c74df68
commit b33b40c9ff
2 changed files with 87 additions and 5 deletions

86
README.md Normal file
View File

@ -0,0 +1,86 @@
# adverr
Package adverr implements errors with call stack traces
as well as error templates for error equality
## Installation
```
go get git.tordarus.net/tordarus/adverr
```
## Usage examples
### Importing
```go
import "git.tordarus.net/tordarus/adverr"
```
### Creating error templates
```go
var (
ErrDoStuffFailed = adverr.NewErrTmpl("ErrDoStuffFailed", "Could'nt do stuff because of %s")
)
```
### Creating independent error (without error template)
```go
func doStuffWithIndependentErr() error {
return adverr.New("Could'nt do stuff")
}
```
### Creating error based on template
```go
func doStuff() error {
return ErrDoStuffFailed.New("reasons")
}
```
### Printing errors on stderr convieniently
```go
adverr.Print(myErr)
adverr.Println(myErr)
```
### Printing errors on stderr and exit with exit code
```go
adverr.Fatal(myErr, 1)
adverr.Fatalln(myErr, 1)
```
### Advantages of error templates
two errors made by the same template will return true when called with `errors.Is()`
```go
func doStuffAndFailWithMsg(msg string) error {
return ErrDoStuffFailed.New(msg)
}
err1 := doStuffAndFailWithMsg("err1")
err2 := doStuffAndFailWithMsg("err2")
fmt.Println(errors.Is(err1, err2)) // true
fmt.Println(err1 == err2) // false
fmt.Println(err1.Error() == err2.Error()) // false
```
### Wrapping errors
By wrapping errors, you can provide an error that is caused by another error.
A 'Caused by' section will be printed in the stack trace showing the original error.
You can also retrieve the original error by using `errors.Unwrap()`
```go
func doStuffWrapped() error {
err := doStuff()
if err != nil {
return adverr.Wrap("doStuffWrapped failed", err)
}
return nil
}
```
### Retrieving call stack trace (for debugging purposes)
```go
fmt.Println(adverr.Trace())
```
###

View File

@ -37,11 +37,7 @@ func errtype(err error) string {
if e, ok := err.(*Error); ok && e.tmpl != nil { if e, ok := err.(*Error); ok && e.tmpl != nil {
return errtype(e.tmpl) return errtype(e.tmpl)
} else if tmpl, ok := err.(*ErrTmpl); ok { } else if tmpl, ok := err.(*ErrTmpl); ok {
t := reflect.TypeOf(tmpl) return tmpl.name
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t.PkgPath() + "." + tmpl.name
} }
t := reflect.TypeOf(err) t := reflect.TypeOf(err)