A Go library for creating, wrapping, and annotating errors with additional context, stack traces, and structured logging support.
- Error Categorization: Use
kind
to categorize errors. - Stack Traces: Automatically captures stack traces when errors are created or wrapped.
- Annotations: Add key-value pairs to errors for additional context.
- Structured Logging: Integrates with
log/slog
for structured error logging. - Error Wrapping: Wrap existing errors while preserving their context.
To install the library, run:
go get github.com/talon-one/errors
Use the New
function to create a new error with a specific kind and message:
import "github.com/talon-one/errors"
err := errors.New("server-side", "an internal server error occurred")
Use the Wrap
function to wrap an existing error with a new kind:
import "github.com/talon-one/errors"
wrappedErr := errors.Wrap("database", err)
Annotating an Error
Use the Annotate
function to add key-value pairs to an error for additional context:
import "github.com/talon-one/errors"
annotatedErr := errors.Annotate(err, "current_user", "[email protected]")
The library integrates with log/slog
for structured logging:
import (
"log/slog"
"github.com/talon-one/errors"
)
err := errors.New("server-side", "an internal server error occurred")
errors.Annotate(err, "current_user", "[email protected]")
slog.Error("an error occurred", "err", err)
{
"time": "2025-01-01T00:00:00.000000+00:00",
"level": "ERROR",
"msg": "an error occurred",
"err": {
"kind": "server-side",
"message": "an internal server error occurred",
"annotations": {
"current_user": "[email protected]"
},
"stacktrace": "github.com/talon-one/errors_test.TestLogNewErrorWithSlog\n\t/.../errors/errors_test.go:20\ntesting.tRunner\n\t/.../src/testing/testing.go:1792\n"
}
}
The library supports custom formatting for errors:
%s
or%q
: Prints the error message.%+v
: Prints the error as a JSON object, including stack trace and annotations.
fmt.Printf("%+v\n", err)
{
"kind": "server-side",
"message": "an internal server error occurred",
"annotations": {
"current_user": "[email protected]"
},
"stacktrace": "github.com/talon-one/errors_test.TestPrintErrorWithFormat\n\t/.../errors/errors_test.go:48\ntesting.tRunner\n\t/.../src/testing/testing.go:1792\n"
}
Run the tests using:
go test ./...
This project is licensed under the MIT License. See the LICENSE file for details.