errwrap is a lightweight, extensible library for structured error handling in Go microservices. It provides consistent formatting, metadata support, and easy integration with both gRPC and HTTP protocols.
go get github.com/flew1x/errwrap- Typed error codes (
ErrorCode) - Rich context with
operationandmetafields - Easy wrapping of internal errors
- Native support for gRPC error mapping (
status.Status) - JSON error output for HTTP APIs
- Domain scoping via configuration
err := errwrap.Wrap("CreateUser", errwrap.CodeConflict, errors.New("user already exists"), map[string]any{
"email": "user@example.com",
})code := errwrap.CodeOf(err)
if code == errwrap.CodeConflict {
// handle conflict case
}return nil, errwrap.ToGRPCStatus(
errwrap.Wrap("GetUser", errwrap.CodeNotFound, errors.New("not found"), map[string]any{
"id": "123",
}),
)This will attach errdetails.ErrorInfo to the status and preserve error metadata.
errwrap.WriteHTTPError(w, errwrap.Wrap("Validate", errwrap.CodeInvalidArgument, errors.New("missing field"), nil))Responds with structured JSON and proper HTTP status:
{
"code": "INVALID_ARGUMENT",
"message": "missing field",
"operation": "Validate"
}Set domain (for tracing, metrics, etc):
errwrap.Configure(
errwrap.WithDomain("billing-service"),
)| Code | Meaning |
|---|---|
CodeUnknown |
Default/fallback error code |
CodeNotFound |
Resource does not exist |
CodeInvalidArgument |
Invalid input data |
CodeConflict |
Conflict (duplicate, already exists) |
CodeUnauthenticated |
Missing or invalid credentials |
CodePermissionDenied |
Access denied |
You can extend this list as needed in your service.
go test -v ./...Includes coverage for:
WrapandCodeOf- HTTP error writing
- gRPC error status generation
- Domain configuration
errwrap/
├── errwrap.go // Core error type and wrapping
├── http.go // HTTP helpers
├── grpc.go // gRPC integration
├── config.go // Global configuration
├── error_code.go // ErrorCode constants
├── *_test.go // Tests
Issues and merge requests are welcome via GitLab. Follow standard Go practices and format code with go fmt.
MIT