chained errors introduced

This commit is contained in:
2021-09-09 16:35:48 +02:00
parent 99f4cca565
commit 53d843e2e3
5 changed files with 135 additions and 8 deletions

View File

@ -78,6 +78,31 @@ func doStuffWrapped() error {
}
```
### Chain errors (Errors caused in succession)
By chaining errors, you can provide an error that represents multiple errors caused in succession inside the same function.
For each chained error a 'Previously thrown' section will be printed in the stack trace.
You can programmatically check chained errors using the following methods:
```go
// Get Returns the first error in the chain for which errors.Is(target) returns true
Get(target error) error
// GetByIndex returns the i'th error in the chain
GetByIndex(i int) error
// Chain returns a slice of all chained errors
Chain() []error
// Contains is a shorthand for Get(target) != nil.
// Can be considered as an errors.Is function but for chains instead of causes
Contains(target error) bool
```
Be aware that the standard library calls wrapped errors chains as well! But these chains are something different. Here is an example use case:
You have a list of files from which you only want to read the first one you have read permissions for. This is most likely done in a loop inside the same function.
A chained error can keep all previously failed read errors and show them in a debuggable way. Wrapping by causality would be ambiguous because they might already have been wrapped multiple times and their causes can therefore not be distinguished from previously failed errors (chained errors).
### Retrieve call stack trace (for debugging purposes)
```go
fmt.Println(adverr.Trace())
@ -156,4 +181,23 @@ adverr.CallStackLength = 50 // default value: 100
If you are in a productive environment, consider disabling call traces completely for performance reasons:
```go
adverr.DisableTrace = true // default value: false
```
```
## Change log
### v0.1.2
Introduced error chaining
### v0.1.1
Improved errors.Is behavior so that ErrTmpl's are considered as targets as well. Example:
```go
err := ErrDoStuffFailed.New("some error")
fmt.Println(errors.Is(err, ErrDoStuffFailed)) // returns true since v0.1.1
```
### v0.1.0
initial release