diff --git a/Packages.md b/Packages.md index 13e2695..254f554 100644 --- a/Packages.md +++ b/Packages.md @@ -35,7 +35,7 @@ Interceptors provides a common set of reusable interceptors for grpc services Documentation can be found at [interceptor-docs] ## [Errors] -errors provides an implementation of golang error with stack strace information attached to it, the error objects created by this package are compatible with https://golang.org/pkg/errors/ +A drop-in replacement for the standard `errors` package that adds stack trace capture and gRPC status codes. Standard library helpers (`Is`, `As`, `Unwrap`, `Join`) are re-exported. Error notification is provided by the [Notifier] sub-package below. Documentation can be found at [errors-docs] diff --git a/howto/errors.md b/howto/errors.md index 68a0bb8..1e20ed5 100644 --- a/howto/errors.md +++ b/howto/errors.md @@ -59,7 +59,6 @@ func somefunction() error { The ColdBrew [errors package] provides a `Wrap` function that can be used to wrap an error with a message. This is useful when you want to add more context to an error. ```go - import ( "github.com/go-coldbrew/errors" ) @@ -76,6 +75,67 @@ func function2() error { } ``` +### Checking errors + +Standard library error helpers (`Is`, `As`, `Unwrap`, `Join`) are re-exported, so you don't need a separate `import "errors"`. Use `errors.Is` to check if an error matches a sentinel value, and `errors.As` to extract a specific error type from the chain: + +```go +import ( + "database/sql" + "fmt" + + "github.com/go-coldbrew/errors" +) + +func handleQuery(err error) { + // Check if an error matches a sentinel value + if errors.Is(err, sql.ErrNoRows) { + // handle not found + } + + // Extract a specific error type from the chain + var ext errors.ErrorExt + if errors.As(err, &ext) { + fmt.Println("gRPC code:", ext.GRPCStatus().Code()) + } +} +``` + +### Finding root cause + +ColdBrew also provides `errors.Cause` to walk the `Unwrap` chain and find the root cause error. This works on any error, not just ColdBrew errors: + +```go +root := errors.Cause(err) // returns the innermost error in the chain +``` + +For ColdBrew errors, you can also use the `Cause()` method on the `ErrorExt` interface, which returns the same result. + +### Combining errors + +Use `errors.Join` to combine multiple errors into a single error: + +```go +err1 := errors.New("first problem") +err2 := errors.New("second problem") +combined := errors.Join(err1, err2) + +// Both errors are preserved in the chain +errors.Is(combined, err1) // true +errors.Is(combined, err2) // true +``` + +### Unwrapping errors + +Use `errors.Unwrap` to get the immediate parent error in the chain: + +```go +base := errors.New("base") +wrapped := errors.Wrap(base, "context") + +inner := errors.Unwrap(wrapped) // returns base +``` + ## ColdBrew notifier package The ColdBrew [notifier package] provides a simple way to notify errors to different notifiers like [Sentry], [Airbrake], [Rollbar] etc.