{"id":13412765,"url":"https://github.com/naughtygopher/errors","last_synced_at":"2025-04-13T08:33:28.542Z","repository":{"id":45454154,"uuid":"280503106","full_name":"naughtygopher/errors","owner":"naughtygopher","description":"A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.","archived":false,"fork":false,"pushed_at":"2025-01-25T09:52:37.000Z","size":78,"stargazers_count":70,"open_issues_count":0,"forks_count":5,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-09T17:01:17.037Z","etag":null,"topics":["awesome-go","awesome-golang","awesome-list","error-handling","errors","go","go-errors","go-library","go-package","golang","golang-errors","golang-library","golang-module","golang-wrapper"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/naughtygopher.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}},"created_at":"2020-07-17T18:57:04.000Z","updated_at":"2025-03-10T11:33:15.000Z","dependencies_parsed_at":"2024-10-14T15:00:55.868Z","dependency_job_id":null,"html_url":"https://github.com/naughtygopher/errors","commit_stats":null,"previous_names":["naughtygopher/errors","bnkamalesh/errors"],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naughtygopher%2Ferrors","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naughtygopher%2Ferrors/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naughtygopher%2Ferrors/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naughtygopher%2Ferrors/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/naughtygopher","download_url":"https://codeload.github.com/naughtygopher/errors/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248610341,"owners_count":21132921,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["awesome-go","awesome-golang","awesome-list","error-handling","errors","go","go-errors","go-library","go-package","golang","golang-errors","golang-library","golang-module","golang-wrapper"],"created_at":"2024-07-30T20:01:28.907Z","updated_at":"2025-04-13T08:33:28.489Z","avatar_url":"https://github.com/naughtygopher.png","language":"Go","readme":"\u003cp align=\"center\"\u003e\u003cimg src=\"https://user-images.githubusercontent.com/1092882/87815217-d864a680-c882-11ea-9c94-24b67f7125fe.png\" alt=\"errors gopher\" width=\"256px\"/\u003e\u003c/p\u003e\n\n[![](https://github.com/naughtygopher/errors/actions/workflows/go.yml/badge.svg?branch=master)](https://github.com/naughtygopher/errors/actions)\n[![Go Reference](https://pkg.go.dev/badge/github.com/naughtygopher/errors.svg)](https://pkg.go.dev/github.com/naughtygopher/errors)\n[![Go Report Card](https://goreportcard.com/badge/github.com/naughtygopher/errors)](https://goreportcard.com/report/github.com/naughtygopher/errors)\n[![Coverage Status](https://coveralls.io/repos/github/naughtygopher/errors/badge.svg?branch=master)](https://coveralls.io/github/naughtygopher/errors?branch=master)\n[![](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go#error-handling)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/creativecreature/sturdyc/blob/master/LICENSE)\n\n# Errors v1.0.0\n\nErrors package is a drop-in replacement of the built-in Go errors package. It lets you create errors of 11 different types,\nwhich should handle most of the use cases. Some of them are a bit too specific for web applications, but useful nonetheless.\n\nFeatures of this package:\n\n1. Multiple (11) error types\n2. Easy handling of User friendly message(s)\n3. Stacktrace - formatted, unfromatted, custom format (refer tests in errors_test.go)\n4. Retrieve the Program Counters for the stacktrace\n5. Retrieve runtime.Frames using `errors.RuntimeFrames(err error)` for the stacktrace\n6. HTTP status code and user friendly message (wrapped messages are concatenated) for all error types\n7. Helper functions to generate each error type\n8. Helper function to get error Type, error type as int, check if error type is wrapped anywhere in chain\n9. `fmt.Formatter` support\n\nIn case of nested errors, the messages \u0026 errors are also looped through the full chain of errors.\n\n### Prerequisites\n\nGo 1.13+\n\n### Available error types\n\n1. TypeInternal - For internal system error. e.g. Database errors\n2. TypeValidation - For validation error. e.g. invalid email address\n3. TypeInputBody - For invalid input data. e.g. invalid JSON\n4. TypeDuplicate - For duplicate content error. e.g. user with email already exists (when trying to register a new user)\n5. TypeUnauthenticated - For not authenticated error\n6. TypeUnauthorized - For unauthorized access error\n7. TypeEmpty - For when an expected non-empty resource, is empty\n8. TypeNotFound - For expected resource not found. e.g. user ID not found\n9. TypeMaximumAttempts - For attempting the same action more than an allowed threshold\n10. TypeSubscriptionExpired - For when a user's 'paid' account has expired\n11. TypeDownstreamDependencyTimedout - For when a request to a downstream dependent service times out\n\nHelper functions are available for all the error types. Each of them have 2 helper functions, one which accepts only a string,\nand the other which accepts an original error as well as a user friendly message.\n\nAll the dedicated error type functions are documented [here](https://pkg.go.dev/github.com/naughtygopher/errors?tab=doc#DownstreamDependencyTimedout).\nNames are consistent with the error type, e.g. errors.Internal(string) and errors.InternalErr(error, string)\n\n### User friendly messages\n\nMore often than not when writing APIs, we'd want to respond with an easier to undersand user friendly message.\nInstead of returning the raw error and log the raw error.\n\nThere are helper functions for all the error types. When in need of setting a friendly message, there\nare helper functions with the _suffix_ **'Err'**. All such helper functions accept the original error and a string.\n\n```golang\npackage main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/naughtygopher/errors\"\n)\n\nfunc Bar() error {\n\treturn fmt.Errorf(\"hello %s\", \"world!\")\n}\n\nfunc Foo() error {\n\terr := Bar()\n\tif err != nil {\n\t\treturn errors.InternalErr(err, \"bar is not happy\")\n\t}\n\treturn nil\n}\n\nfunc main() {\n\terr := Foo()\n\n\tfmt.Println(\"err:\", err)\n\tfmt.Println(\"\\nerr.Error():\", err.Error())\n\n\tfmt.Printf(\"\\nformatted +v: %+v\\n\", err)\n\tfmt.Printf(\"\\nformatted v: %v\\n\", err)\n\tfmt.Printf(\"\\nformatted +s: %+s\\n\", err)\n\tfmt.Printf(\"\\nformatted s: %s\\n\", err)\n\n\t_, msg, _ := errors.HTTPStatusCodeMessage(err)\n\tfmt.Println(\"\\nmsg:\", msg)\n}\n```\n\nOutput\n\n```\nerr: bar is not happy\n\nerr.Error(): /Users/k.balakumaran/go/src/github.com/naughtygopher/errors/cmd/main.go:16: bar is not happy\nhello world!bar is not happy\n\nformatted +v: /Users/k.balakumaran/go/src/github.com/naughtygopher/errors/cmd/main.go:16: bar is not happy\nhello world!bar is not happy\n\nformatted v: bar is not happy\n\nformatted +s: bar is not happy: hello world!\n\nformatted s: bar is not happy\n\nmsg: bar is not happy\n```\n\n[Playground link](https://go.dev/play/p/-WzDH46f_U5)\n\n### File \u0026 line number prefixed to errors\n\nA common annoyance with Go errors which most people are aware of is, figuring out the origin of the error, especially when there are nested function calls. Ever since error annotation was introduced in Go, a lot of people have tried using it to trace out an errors origin by giving function names, contextual message etc in it. e.g. `fmt.Errorf(\"database query returned error %w\", err)`. However this errors package, whenever you call the Go error interface's `Error() string` function, prints the error prefixed by the filepath and line number. It'd look like `../Users/JohnDoe/apps/main.go:50 hello world` where 'hello world' is the error message.\n\n### HTTP status code \u0026 message\n\nThe function `errors.HTTPStatusCodeMessage(error) (int, string, bool)` returns the HTTP status code, message, and a boolean value. The boolean is true, if the error is of type \\*Error from this package. If error is nested, it unwraps and returns a single concatenated message. Sample described in the 'How to use?' section\n\n## How to use?\n\nA sample was already shown in the user friendly message section, following one would show a few more scenarios.\n\n```golang\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/naughtygopher/errors\"\n\t\"github.com/naughtygopher/webgo/v6\"\n\t\"github.com/naughtygopher/webgo/v6/middleware/accesslog\"\n)\n\nfunc bar() error {\n\treturn fmt.Errorf(\"%s %s\", \"sinking\", \"bar\")\n}\n\nfunc bar2() error {\n\terr := bar()\n\tif err != nil {\n\t\treturn errors.InternalErr(err, \"bar2 was deceived by bar1 :(\")\n\t}\n\treturn nil\n}\n\nfunc foo() error {\n\terr := bar2()\n\tif err != nil {\n\t\treturn errors.InternalErr(err, \"we lost bar2!\")\n\t}\n\treturn nil\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\terr := foo()\n\tif err != nil {\n\t\t// log the error on your server for troubleshooting\n\t\tfmt.Println(err.Error())\n\t\t// respond to request with friendly msg\n\t\tstatus, msg, _ := errors.HTTPStatusCodeMessage(err)\n\t\twebgo.SendError(w, msg, status)\n\t\treturn\n\t}\n\n\twebgo.R200(w, \"yay!\")\n}\n\nfunc routes() []*webgo.Route {\n\treturn []*webgo.Route{\n\t\t{\n\t\t\tName:    \"home\",\n\t\t\tMethod:  http.MethodGet,\n\t\t\tPattern: \"/\",\n\t\t\tHandlers: []http.HandlerFunc{\n\t\t\t\thandler,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc main() {\n\trouter := webgo.NewRouter(\u0026webgo.Config{\n\t\tHost:         \"\",\n\t\tPort:         \"8080\",\n\t\tReadTimeout:  15 * time.Second,\n\t\tWriteTimeout: 60 * time.Second,\n\t}, routes()...)\n\n\trouter.UseOnSpecialHandlers(accesslog.AccessLog)\n\trouter.Use(accesslog.AccessLog)\n\trouter.Start()\n}\n```\n\n[webgo](https://github.com/naughtygopher/webgo) was used to illustrate the usage of the function, `errors.HTTPStatusCodeMessage`. It returns the appropriate http status code, user friendly message stored within, and a boolean value. Boolean value is `true` if the returned error of type \\*Error.\nSince we get the status code and message separately, when using any web framework, you can set values according to the respective framework's native functions. In case of Webgo, it wraps errors in a struct of its own. Otherwise, you could directly respond to the HTTP request by calling `errors.WriteHTTP(error,http.ResponseWriter)`.\n\nOnce the app is running, you can check the response by opening `http://localhost:8080` on your browser. Or on terminal\n\n```bash\n$ curl http://localhost:8080\n{\"errors\":\"we lost bar2!. bar2 was deceived by bar1 :(\",\"status\":500} // output\n```\n\nAnd the `fmt.Println(err.Error())` generated output on stdout would be:\n\n```bash\n/Users/username/go/src/errorscheck/main.go:28 /Users/username/go/src/errorscheck/main.go:20 sinking bar\n```\n\n## Benchmark [2022-01-12]\n\nMacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports), 32 GB 3733 MHz LPDDR4X\n\n```bash\n$ go version\ngo version go1.19.5 darwin/amd64\n\n$ go test -benchmem -bench .\ngoos: darwin\ngoarch: amd64\npkg: github.com/naughtygopher/errors\ncpu: Intel(R) Core(TM) i7-1068NG7 CPU @ 2.30GHz\nBenchmark_Internal-8                            \t 1526194\t       748.8 ns/op\t    1104 B/op\t       2 allocs/op\nBenchmark_Internalf-8                           \t 1281465\t       944.0 ns/op\t    1128 B/op\t       3 allocs/op\nBenchmark_InternalErr-8                         \t 1494351\t       806.7 ns/op\t    1104 B/op\t       2 allocs/op\nBenchmark_InternalGetError-8                    \t  981162\t      1189 ns/op\t    1528 B/op\t       6 allocs/op\nBenchmark_InternalGetErrorWithNestedError-8     \t  896322\t      1267 ns/op\t    1544 B/op\t       6 allocs/op\nBenchmark_InternalGetMessage-8                  \t 1492812\t       804.2 ns/op\t    1104 B/op\t       2 allocs/op\nBenchmark_InternalGetMessageWithNestedError-8   \t 1362092\t       886.3 ns/op\t    1128 B/op\t       3 allocs/op\nBenchmark_HTTPStatusCodeMessage-8               \t27494096\t        41.38 ns/op\t      16 B/op\t       1 allocs/op\nBenchmarkHasType-8                              \t100000000\t        10.50 ns/op\t       0 B/op\t       0 allocs/op\nPASS\nok  \tgithub.com/naughtygopher/errors\t15.006s\n```\n\n## Contributing\n\nMore error types, customization, features, multi-errors; PRs \u0026 issues are welcome!\n\n## The gopher\n\nThe gopher used here was created using [Gopherize.me](https://gopherize.me/). Show some love to Go errors like our gopher lady here!\n","funding_links":[],"categories":["Error Handling","Error handling","错误处理"],"sub_categories":["Search and Analytic Databases","Advanced Console UIs","internal/server/http/web/templates","检索及分析资料库"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnaughtygopher%2Ferrors","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnaughtygopher%2Ferrors","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnaughtygopher%2Ferrors/lists"}