wrappederror/README.md

47 lines
941 B
Markdown
Raw Normal View History

2023-09-26 08:46:03 +02:00
```go
2023-09-26 08:45:33 +02:00
package main
import (
2024-09-27 07:43:50 +02:00
// External
werr "git.gibonuddevalla.se/go/wrappederror"
2023-09-26 08:45:33 +02:00
2024-09-27 07:43:50 +02:00
// Standard
"encoding/json"
"errors"
"fmt"
"os"
2023-09-26 08:45:33 +02:00
)
func errorHandler(err werr.Error) {
2024-09-27 07:43:50 +02:00
// For example print or log error to file
fmt.Printf("\x1b[31;1m%s\x1b[0m\n", err)
fmt.Printf("\x1b[33;1m%s\x1b[0m\n", err.NoTrace())
j, _ := json.MarshalIndent(err, "", " ")
fmt.Printf("%s\n\n", j)
2023-09-26 08:45:33 +02:00
}
2024-09-27 07:43:50 +02:00
func main() {
// Make file paths relative to this file.
werr.Init()
// Handler to call when using Log().
werr.SetLogCallback(errorHandler)
// Wrap an existing error.
err := errors.New("foobar 1")
err1 := werr.Wrap(err)
// Create a new error with extra information.
err2 := werr.New("foobar 2").WithCode("FOO-100").WithData(137)
2023-09-26 08:45:33 +02:00
2024-09-27 07:43:50 +02:00
// The os error contains more information.
_, errOS := os.ReadFile("/tmp/does_not_exist")
werr.Wrap(errOS).Log()
2023-09-26 08:45:33 +02:00
2024-09-27 07:43:50 +02:00
// Log the previously wrapped errors.
werr.Wrap(err1).Log()
werr.Wrap(err2).Log()
2023-09-26 08:45:33 +02:00
}
```