|
| 1 | +# serror |
| 2 | + |
| 3 | +[](https://pkg.go.dev/github.com/jetify-com/serror) |
| 4 | +[](https://goreportcard.com/report/github.com/jetify-com/serror) |
| 5 | +[](LICENSE) |
| 6 | + |
| 7 | +An error handling library for Go that makes it easy to associate arbitrary structured data with errors |
| 8 | +in a similar way to what `slog` does for logging. |
| 9 | + |
| 10 | +## Table of Contents |
| 11 | + |
| 12 | +- [Overview](#overview) |
| 13 | +- [Features](#features) |
| 14 | +- [Installation](#installation) |
| 15 | +- [Quick Start](#quick-start) |
| 16 | +- [Key Concepts](#key-concepts) |
| 17 | +- [Design Philosophy](#design-philosophy) |
| 18 | +- [Contributing](#contributing) |
| 19 | +- [License](#license) |
| 20 | +- [Credits](#credits) |
| 21 | + |
| 22 | +## Overview |
| 23 | +`serror` provides a clean API for creating, wrapping, and logging errors with associated structured data. |
| 24 | + |
| 25 | +When handling errors in Go, developers often need to include contextual information to help diagnose what went wrong. The traditional approach using `fmt.Errorf` interpolates this data into a string: |
| 26 | + |
| 27 | +```go |
| 28 | +return fmt.Errorf("failed to process user %d: %w", userID, err) |
| 29 | +``` |
| 30 | + |
| 31 | +While simple, this approach has limitations: |
| 32 | +- The contextual data (like `userID`) becomes just part of the error message |
| 33 | +- There's no way to programmatically access these values later |
| 34 | +- The data loses its type information |
| 35 | +- The format becomes rigid and harder to parse |
| 36 | + |
| 37 | +`serror` solves these problems by allowing you to attach structured data to errors: |
| 38 | + |
| 39 | +```go |
| 40 | +return serror.Wrap(err, "failed to process user", |
| 41 | + "user_id", userID, |
| 42 | + "attempt", attempt, |
| 43 | + "status", status, |
| 44 | +) |
| 45 | +``` |
| 46 | + |
| 47 | +This approach: |
| 48 | +- Preserves the original data types |
| 49 | +- Makes values accessible programmatically via `err.Get("user_id")` |
| 50 | +- Integrates seamlessly with structured logging |
| 51 | +- Maintains the flexibility to add or modify context |
| 52 | + |
| 53 | +Inspired by Go's `log/slog` package, `serror` uses the same familiar key-value pair pattern for attaching attributes. If you've used `slog`, you'll feel right at home: |
| 54 | + |
| 55 | +```go |
| 56 | +// slog style |
| 57 | +logger.Error("request failed", |
| 58 | + "user_id", userID, |
| 59 | + "status", status, |
| 60 | +) |
| 61 | + |
| 62 | +// serror follows the same pattern |
| 63 | +return serror.New("request failed", |
| 64 | + "user_id", userID, |
| 65 | + "status", status, |
| 66 | +) |
| 67 | +``` |
| 68 | + |
| 69 | +## Features |
| 70 | + |
| 71 | +- **Structured Attributes**: Attach key-value pairs to errors using `slog`-like syntax |
| 72 | +- **Error Wrapping**: Fully compatible with Go's error wrapping conventions |
| 73 | +- **slog Integration**: Implements `LogValuer` for automatic structured logging |
| 74 | +- **JSON Support**: Full JSON marshaling/unmarshaling capabilities |
| 75 | +- **Attribute Access**: Get attributes using dot notation (e.g., "user.id") |
| 76 | +- **Thread Safety**: Immutable design ensures safe concurrent usage |
| 77 | +- **Call Site Capture**: Automatically records where errors are created |
| 78 | + |
| 79 | +## Installation |
| 80 | + |
| 81 | +### Using go get |
| 82 | +```bash |
| 83 | +go get github.com/jetify-com/serror |
| 84 | +``` |
| 85 | + |
| 86 | +### From Source |
| 87 | +```bash |
| 88 | +git clone https://github.com/jetify-com/serror.git |
| 89 | +cd serror |
| 90 | +go install |
| 91 | +``` |
| 92 | + |
| 93 | +## Quick Start |
| 94 | + |
| 95 | +```go |
| 96 | +// Create a new error with attributes |
| 97 | +err := serror.New("failed to process request", |
| 98 | + "userID", 123, |
| 99 | + "path", "/api/v1/users", |
| 100 | +) |
| 101 | + |
| 102 | +// Wrap an existing error with additional context |
| 103 | +if err != nil { |
| 104 | + return serror.Wrap(err, "user operation failed", |
| 105 | + "operation", "create", |
| 106 | + "retry", false, |
| 107 | + ) |
| 108 | +} |
| 109 | + |
| 110 | +// Log the error with slog |
| 111 | +slog.Error("request failed", "err", err) |
| 112 | +``` |
| 113 | + |
| 114 | +## Key Concepts |
| 115 | + |
| 116 | +### Creating Errors |
| 117 | + |
| 118 | +```go |
| 119 | +// Basic error with attributes |
| 120 | +err := serror.New("operation failed", |
| 121 | + "code", 500, |
| 122 | + "component", "database", |
| 123 | +) |
| 124 | + |
| 125 | +// Using attribute constructors |
| 126 | +err := serror.New("validation failed", |
| 127 | + serror.Int("code", 400), |
| 128 | + serror.String("field", "email"), |
| 129 | + serror.Bool("valid", false), |
| 130 | +) |
| 131 | + |
| 132 | +// Group related attributes |
| 133 | +err := serror.New("validation failed", |
| 134 | + serror.Group("user", |
| 135 | + serror.Int("id", 123), |
| 136 | + serror.String("name", "alice"), |
| 137 | + ), |
| 138 | +) |
| 139 | +``` |
| 140 | + |
| 141 | +### Wrapping Errors |
| 142 | + |
| 143 | +```go |
| 144 | +baseErr := serror.New("database error", |
| 145 | + "table", "users", |
| 146 | +) |
| 147 | + |
| 148 | +err := serror.Wrap(baseErr, "query failed", |
| 149 | + "query_id", "abc123", |
| 150 | +) |
| 151 | +``` |
| 152 | + |
| 153 | +### Adding Attributes |
| 154 | + |
| 155 | +```go |
| 156 | +// Add more attributes to an existing error |
| 157 | +// Note: With() returns a new error - serror errors are immutable |
| 158 | +oldErr := serror.New("operation failed", "code", 500) |
| 159 | +newErr := oldErr.With("retry", true, "attempt", 3) |
| 160 | + |
| 161 | +// oldErr is unchanged, newErr has all attributes |
| 162 | +``` |
| 163 | + |
| 164 | +The immutable design ensures thread safety and prevents accidental modifications. Each call to `With()` returns a new error instance with the combined attributes from the original error plus the new ones. |
| 165 | + |
| 166 | +### Accessing Attributes |
| 167 | + |
| 168 | +```go |
| 169 | +// Get attribute values using dot notation |
| 170 | +value := err.Get("user.id") |
| 171 | +name := err.Get("user.name") |
| 172 | +``` |
| 173 | + |
| 174 | +### JSON Support |
| 175 | + |
| 176 | +```go |
| 177 | +// Marshal to JSON |
| 178 | +data, err := json.Marshal(serror) |
| 179 | + |
| 180 | +// Unmarshal from JSON |
| 181 | +var newErr serror.Error |
| 182 | +err := json.Unmarshal(data, &newErr) |
| 183 | +``` |
| 184 | + |
| 185 | +### Integration with slog |
| 186 | + |
| 187 | +```go |
| 188 | +err := serror.New("operation failed", |
| 189 | + "user_id", 123, |
| 190 | + "status", 500, |
| 191 | +) |
| 192 | + |
| 193 | +// serror.Error implements slog.LogValuer |
| 194 | +logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) |
| 195 | +logger.Error("request failed", "err", err) |
| 196 | + |
| 197 | +// Output: |
| 198 | +// ERROR request failed err.user_id=123 err.status=500 err.msg="operation failed" |
| 199 | +``` |
| 200 | + |
| 201 | +When logged, all structured attributes are automatically included in the log output, making it easy to correlate errors with their context. |
| 202 | + |
| 203 | +## Design Philosophy |
| 204 | + |
| 205 | +- **Standard Library Aligned**: Works with `errors.Is`, `errors.As`, `errors.Unwrap` |
| 206 | +- **slog Compatible**: Follows `slog` patterns for attribute handling |
| 207 | +- **Thread Safe**: Immutable design prevents data races |
| 208 | +- **Simple API**: Familiar interface for Go developers |
| 209 | + |
| 210 | +## Documentation |
| 211 | + |
| 212 | +For detailed documentation and API references, please visit our [Go Package Documentation](https://pkg.go.dev/github.com/jetify-com/serror). |
| 213 | + |
| 214 | +## Contributing |
| 215 | + |
| 216 | +Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change. |
| 217 | + |
| 218 | +Please make sure to update tests as appropriate. |
| 219 | + |
| 220 | +## Community |
| 221 | + |
| 222 | +- **Issues:** [GitHub Issues](https://github.com/jetify-com/serror/issues) |
| 223 | +- **Discussions:** [GitHub Discussions](https://github.com/jetify-com/serror/discussions) |
| 224 | + |
| 225 | +## License |
| 226 | + |
| 227 | +This project is licensed under the Apache License, Version 2.0 - see the [LICENSE](LICENSE) file for details. |
| 228 | + |
| 229 | +## Acknowledgments |
| 230 | + |
| 231 | +- Thanks to the Go team for the excellent `log/slog` package design |
| 232 | +- Inspired by various error handling patterns in the Go community |
0 commit comments