{"id":19561352,"url":"https://github.com/m-mizutani/goerr","last_synced_at":"2026-02-02T01:15:06.954Z","repository":{"id":57210099,"uuid":"356424478","full_name":"m-mizutani/goerr","owner":"m-mizutani","description":"More contextual error handling in Go","archived":false,"fork":false,"pushed_at":"2025-09-19T00:38:10.000Z","size":170,"stargazers_count":42,"open_issues_count":0,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-12-22T19:45:38.617Z","etag":null,"topics":["error-handling","go"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-2-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/m-mizutani.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2021-04-09T23:49:48.000Z","updated_at":"2025-12-21T17:55:31.000Z","dependencies_parsed_at":"2024-01-13T08:29:28.560Z","dependency_job_id":"cfbc22dc-c908-4412-a5c7-f1e8a5bb01b1","html_url":"https://github.com/m-mizutani/goerr","commit_stats":null,"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"purl":"pkg:github/m-mizutani/goerr","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/m-mizutani%2Fgoerr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/m-mizutani%2Fgoerr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/m-mizutani%2Fgoerr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/m-mizutani%2Fgoerr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/m-mizutani","download_url":"https://codeload.github.com/m-mizutani/goerr/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/m-mizutani%2Fgoerr/sbom","scorecard":{"id":608030,"data":{"date":"2025-08-11","repo":{"name":"github.com/m-mizutani/goerr","commit":"0ccee1a1b3d1eb56c8442766b6f2034d812762c6"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":4.2,"checks":[{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Code-Review","score":0,"reason":"Found 0/18 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Maintained","score":1,"reason":"2 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 1","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/gosec.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/m-mizutani/goerr/gosec.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/gosec.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/m-mizutani/goerr/gosec.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/gosec.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/m-mizutani/goerr/gosec.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/m-mizutani/goerr/test.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/m-mizutani/goerr/test.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/trivy.yml:11: update your workflow using https://app.stepsecurity.io/secureworkflow/m-mizutani/goerr/trivy.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/trivy.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/m-mizutani/goerr/trivy.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/trivy.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/m-mizutani/goerr/trivy.yml/main?enable=pin","Info:   0 out of   6 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   2 third-party GitHubAction dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/gosec.yml:1","Warn: no topLevel permission defined: .github/workflows/test.yml:1","Warn: no topLevel permission defined: .github/workflows/trivy.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: BSD 2-Clause \"Simplified\" License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'main'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"SAST","score":10,"reason":"SAST tool is run on all commits","details":["Info: all commits (25) are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}}]},"last_synced_at":"2025-08-21T02:02:53.068Z","repository_id":57210099,"created_at":"2025-08-21T02:02:53.068Z","updated_at":"2025-08-21T02:02:53.068Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28998370,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-01T23:10:54.274Z","status":"ssl_error","status_checked_at":"2026-02-01T23:10:47.298Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["error-handling","go"],"created_at":"2024-11-11T05:11:11.363Z","updated_at":"2026-02-02T01:15:06.949Z","avatar_url":"https://github.com/m-mizutani.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# goerr [![test](https://github.com/m-mizutani/goerr/actions/workflows/test.yml/badge.svg)](https://github.com/m-mizutani/goerr/actions/workflows/test.yml) [![gosec](https://github.com/m-mizutani/goerr/actions/workflows/gosec.yml/badge.svg)](https://github.com/m-mizutani/goerr/actions/workflows/gosec.yml) [![package scan](https://github.com/m-mizutani/goerr/actions/workflows/trivy.yml/badge.svg)](https://github.com/m-mizutani/goerr/actions/workflows/trivy.yml) [![Go Reference](https://pkg.go.dev/badge/github.com/m-mizutani/goerr.svg)](https://pkg.go.dev/github.com/m-mizutani/goerr/v2)\n\nEnhanced error handling for Go with stack traces, contextual values, and structured logging\n\n## Overview\n\n`goerr` is a powerful error handling library for Go that enhances errors with rich contextual information. It provides stack traces, contextual variables, error categorization, and seamless integration with structured logging - all while maintaining full compatibility with Go's standard error handling patterns.\n\n## Key Features\n\n- **Stack Traces**: Automatic capture with `github.com/pkg/errors` compatibility\n- **Contextual Data**: Attach key-value pairs and tags to errors\n- **Type Safety**: Compile-time type checking for error context\n- **Multiple Errors**: Aggregate errors with `goerr.Errors`\n- **Structured Logging**: Native `slog` integration\n\n## Installation\n\n```sh\ngo get github.com/m-mizutani/goerr/v2\n```\n\n## Quick Start\n\n```go\npackage main\n\nimport (\n    \"log\"\n    \"github.com/m-mizutani/goerr/v2\"\n)\n\nfunc main() {\n    if err := processFile(\"data.txt\"); err != nil {\n        // Print error with stack trace\n        log.Fatalf(\"%+v\", err)\n    }\n}\n\nfunc processFile(filename string) error {\n    _, err := readFile(filename)\n    if err != nil {\n        return goerr.Wrap(err, \"failed to process file\",\n            goerr.Value(\"filename\", filename))\n    }\n    return nil\n}\n\nfunc readFile(filename string) error {\n    // Simulate error\n    return goerr.New(\"file not found\")\n}\n```\n\n## Core Features\n\n### Error Creation and Wrapping\n\nCreate new errors or wrap existing ones with additional context:\n\n```go\n// Create a new error\nerr := goerr.New(\"validation failed\")\n\n// Wrap an existing error\nif err := someFunc(); err != nil {\n    return goerr.Wrap(err, \"operation failed\")\n}\n\n// Add contextual information without changing the original error\nerr = goerr.With(err,\n    goerr.Value(\"user_id\", userID),\n    goerr.Value(\"timestamp\", time.Now()))\n\n// With preserves stacktrace for goerr.Error, wraps standard errors\noriginalErr := goerr.New(\"original error\")\nenhanced := goerr.With(originalErr, goerr.Value(\"context\", \"added\"))\n// enhanced has same stacktrace as originalErr, originalErr unchanged\n\n// Key precedence: later values override earlier ones\nerr := goerr.New(\"error\", goerr.Value(\"key\", \"first\"))\nenhanced := goerr.With(err,\n    goerr.Value(\"key\", \"second\"),  // Overrides \"first\"\n    goerr.Value(\"key\", \"final\"))   // Overrides \"second\"\n// enhanced.Values()[\"key\"] == \"final\"\n\n// Extract goerr.Error from any error\nif goErr := goerr.Unwrap(err); goErr != nil {\n    values := goErr.Values() // Get all contextual values\n}\n```\n\n### Multiple Error Handling\n\nAggregate multiple errors with `goerr.Errors`:\n\n```go\n// Collect errors during processing\nvar errs *goerr.Errors\nfor _, item := range items {\n    if err := processItem(item); err != nil {\n        errs = goerr.Append(errs, err)  // nil-safe\n    }\n}\n\n// Return only if errors occurred\nreturn errs.ErrorOrNil()  // nil if no errors\n\n// Join errors directly\ncombined := goerr.Join(err1, err2, err3)\n\n// All errors displayed together\nfmt.Printf(\"%v\", combined)\n// Output: error1\\nerror2\\nerror3\n\n// Works with standard library\nif errors.Is(combined, err1) { /* true */ }\n```\n\n### Contextual Data\n\n**String-based Values**\n\nAttach arbitrary key-value pairs to errors:\n\n```go\nfunc validateUser(userID string, age int) error {\n    if age \u003c 18 {\n        return goerr.New(\"user too young\",\n            goerr.V(\"user_id\", userID),  // V is alias for Value\n            goerr.V(\"age\", age),\n            goerr.V(\"required_age\", 18))\n    }\n    return nil\n}\n\n// Extract values from error\nif err := validateUser(\"user123\", 16); err != nil {\n    if goErr := goerr.Unwrap(err); goErr != nil {\n        for key, value := range goErr.Values() {\n            log.Printf(\"%s: %v\", key, value)\n        }\n    }\n}\n```\n\n**Type-safe Values**\n\nUse compile-time type checking for error context:\n\n```go\n// Define typed keys (typically at package level)\nvar (\n    UserIDKey    = goerr.NewTypedKey[string](\"user_id\")\n    RequestIDKey = goerr.NewTypedKey[int64](\"request_id\")\n    ConfigKey    = goerr.NewTypedKey[*Config](\"config\")\n)\n\n// Use typed values - compile-time type checking\nerr := goerr.New(\"validation failed\",\n    goerr.TV(UserIDKey, \"user123\"),      // Must be string\n    goerr.TV(RequestIDKey, int64(42)),   // Must be int64\n    goerr.TV(ConfigKey, currentConfig))  // Must be *Config\n\n// Retrieve typed values - no type assertion needed\nif userID, ok := goerr.GetTypedValue(err, UserIDKey); ok {\n    // userID is string type, guaranteed\n    fmt.Printf(\"User: %s\\n\", userID)\n}\n```\n\n**Error Tags**\n\nCategorize errors for different handling strategies:\n\n```go\n// Define tags\nvar (\n    ErrTagNotFound   = goerr.NewTag(\"not_found\")\n    ErrTagValidation = goerr.NewTag(\"validation\")\n    ErrTagExternal   = goerr.NewTag(\"external\")\n)\n\n// Tag errors\nif user == nil {\n    return goerr.New(\"user not found\",\n        goerr.T(ErrTagNotFound))  // T is alias for Tag\n}\n\n// Handle errors based on tags\nif goerr.HasTag(err, ErrTagNotFound) {\n    w.WriteHeader(http.StatusNotFound)\n} else if goerr.HasTag(err, ErrTagValidation) {\n    w.WriteHeader(http.StatusBadRequest)\n} else {\n    w.WriteHeader(http.StatusInternalServerError)\n}\n```\n\n### Stack Traces\n\nStack traces are automatically captured and compatible with `github.com/pkg/errors`:\n\n```go\nfunc doWork() error {\n    return goerr.New(\"something went wrong\")\n}\n\nfunc main() {\n    if err := doWork(); err != nil {\n        // Print with stack trace using %+v\n        log.Printf(\"%+v\", err)\n        \n        // Extract stack programmatically\n        if goErr := goerr.Unwrap(err); goErr != nil {\n            for _, frame := range goErr.Stacks() {\n                log.Printf(\"  at %s:%d in %s\", \n                    frame.File, frame.Line, frame.Func)\n            }\n        }\n    }\n}\n\n// Remove current frame from stack (useful for helper functions)\nfunc helperFunc() error {\n    return goerr.New(\"error from helper\").Unstack()\n}\n```\n\n## Advanced Features\n\n### Enhancing Errors with Context\n\nThe `With` function adds contextual information to errors without modifying the original:\n\n```go\n// For goerr.Error: preserves existing stacktrace\noriginalErr := goerr.New(\"database connection failed\")\nenhanced := goerr.With(originalErr,\n    goerr.Value(\"host\", \"db.example.com\"),\n    goerr.Value(\"port\", 5432),\n    goerr.Tag(ErrTagExternal))\n\n// originalErr remains unchanged, enhanced has same stacktrace\nfmt.Printf(\"Original unchanged: %v\\n\", originalErr.Values()) // empty\nfmt.Printf(\"Enhanced: %v\\n\", enhanced.Values())              // has host, port\n\n// For standard errors: wraps with new stacktrace\nstdErr := errors.New(\"file not found\")\nenhanced2 := goerr.With(stdErr, goerr.Value(\"path\", \"/tmp/file.txt\"))\n// enhanced2 wraps stdErr with new stacktrace and context\n```\n\n### Error Identification\n\nUse IDs for flexible error comparison:\n\n```go\nvar (\n    ErrInvalidInput = goerr.New(\"invalid input\", goerr.ID(\"ERR_INVALID_INPUT\"))\n    ErrTimeout      = goerr.New(\"operation timeout\", goerr.ID(\"ERR_TIMEOUT\"))\n)\n\nfunc process() error {\n    return goerr.Wrap(ErrInvalidInput, \"validation failed\",\n        goerr.Value(\"field\", \"email\"))\n}\n\n// Check error identity\nif err := process(); err != nil {\n    if errors.Is(err, ErrInvalidInput) {\n        // Matches by ID, not pointer\n        handleValidationError(err)\n    }\n}\n```\n\n### Builder Pattern\n\nCreate multiple errors with shared context:\n\n```go\ntype Service struct {\n    userID string\n    reqID  string\n}\n\nfunc (s *Service) process() error {\n    // Create builder with common context\n    eb := goerr.NewBuilder(\n        goerr.Value(\"user_id\", s.userID),\n        goerr.Value(\"request_id\", s.reqID))\n    \n    // Use builder for multiple errors\n    if err := s.validate(); err != nil {\n        return eb.Wrap(err, \"validation failed\")\n    }\n    \n    if err := s.save(); err != nil {\n        return eb.Wrap(err, \"save failed\")\n    }\n    \n    return nil\n}\n```\n\n### Structured Logging\n\nNative integration with Go's `slog` package:\n\n```go\nlogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))\n\nerr := goerr.New(\"database error\",\n    goerr.Value(\"table\", \"users\"),\n    goerr.Value(\"operation\", \"insert\"))\n\n// Error implements slog.LogValuer\nlogger.Error(\"operation failed\", slog.Any(\"error\", err))\n\n// Output (formatted):\n// {\n//   \"level\": \"ERROR\",\n//   \"msg\": \"operation failed\",\n//   \"error\": {\n//     \"message\": \"database error\",\n//     \"values\": {\"table\": \"users\", \"operation\": \"insert\"},\n//     \"stacktrace\": [...]\n//   }\n// }\n```\n\n### JSON Serialization\n\nExport full error details as JSON:\n\n```go\nerr := goerr.New(\"validation error\",\n    goerr.Value(\"field\", \"email\"),\n    goerr.Tag(ValidationTag))\n\n// Get JSON-serializable struct\nprintable := goerr.Unwrap(err).Printable()\n\n// Or marshal directly\njsonData, _ := json.Marshal(err)\n\n// Output includes message, stack trace, values, tags, and cause chain\n```\n\n## Examples\n\nSee the [examples](./examples) directory for complete working examples:\n- Stack trace handling\n- Contextual variables\n- Multiple error aggregation\n- HTTP error responses\n- Sentry integration\n- Structured logging with slog\n- And more...\n\n## Migration Guide\n\nSee [Migration Guide](./docs/migration.md) for migrating from:\n- `github.com/pkg/errors`\n- Standard library `errors` package\n- goerr v1 to v2\n\n## License\n\nThe 2-Clause BSD License. See [LICENSE](LICENSE) for more detail.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fm-mizutani%2Fgoerr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fm-mizutani%2Fgoerr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fm-mizutani%2Fgoerr/lists"}