{"id":31737399,"url":"https://github.com/chenhaojie9527/go-style-error","last_synced_at":"2025-10-09T09:12:33.893Z","repository":{"id":305101916,"uuid":"1021854083","full_name":"ChenHaoJie9527/go-style-error","owner":"ChenHaoJie9527","description":"An elegant JavaScript/TypeScript asynchronous error handling library inspired by the Go language's error handling model.","archived":false,"fork":false,"pushed_at":"2025-07-18T07:26:53.000Z","size":42,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-18T11:09:38.877Z","etag":null,"topics":["api","async","http","promise","request"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/go-style-error","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ChenHaoJie9527.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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}},"created_at":"2025-07-18T03:59:42.000Z","updated_at":"2025-07-18T08:13:54.000Z","dependencies_parsed_at":"2025-07-18T11:10:37.793Z","dependency_job_id":"8fad6378-5ebf-4089-bbba-78bb66e84548","html_url":"https://github.com/ChenHaoJie9527/go-style-error","commit_stats":null,"previous_names":["chenhaojie9527/do"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/ChenHaoJie9527/go-style-error","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ChenHaoJie9527%2Fgo-style-error","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ChenHaoJie9527%2Fgo-style-error/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ChenHaoJie9527%2Fgo-style-error/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ChenHaoJie9527%2Fgo-style-error/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ChenHaoJie9527","download_url":"https://codeload.github.com/ChenHaoJie9527/go-style-error/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ChenHaoJie9527%2Fgo-style-error/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279001123,"owners_count":26083021,"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","status":"online","status_checked_at":"2025-10-09T02:00:07.460Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["api","async","http","promise","request"],"created_at":"2025-10-09T09:09:54.777Z","updated_at":"2025-10-09T09:12:33.885Z","avatar_url":"https://github.com/ChenHaoJie9527.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# go-style-error\n\nAn elegant JavaScript/TypeScript asynchronous error handling library inspired by the Go language's error handling model.\n\n## ✨ Features\n\n- 🚀 **Zero Dependencies** - Lightweight, no external dependencies\n- 🎯 **Type-safe** - full TypeScript support\n- 🔄 **Go style** - returns `[error, data]` tuples, avoiding the cumbersome syntax of try-catch\n- 🛡️ **Elegant Degradation** - support default values for more elegant error handling\n- 📦 **Multi-format** - support for CommonJS and ES Modules\n- 🧪 **Fully tested** - 100% test coverage\n\n## 📦 Installation\n\n```bash\nnpm install go-style-error\n# or\nyarn add go-style-error\n# or\npnpm add go-style-error\n```\n\n## 🚀 Quick start\n\n### basic usage\n\n```typescript\nimport { to } from 'go-style-error';\n\n// traditional approach\ntry {\n  const user = await fetchUser(id);\n  console.log(user);\n} catch (error) {\n  console.error('Failed to fetch user:', error.message);\n}\n\n// Using the go-style-error Library\nconst [error, user] = await to(() =\u003e fetchUser(id));\nif (error) {\n  console.error('Failed to fetch user:', error.message);\n  return;\n}\nconsole.log(user);\n```\n\n### Error handling with default values\n\n```typescript\nimport { to } from 'go-style-error';\n\n// If the API call fails, use the default\nconst [error, users] = await to(() =\u003e fetchUsers(), []);\n// users will be [] if fetchUsers() fails\n\n// Error Handling with Default Objects\nconst [error, settings] = await to(\n  () =\u003e fetchUserSettings(userId),\n  { theme: 'light', notifications: false }\n);\n\n### 📚 API reference\n\n### `to\u003cT\u003e(asyncFn, defaultValue?)`\n\nExecutes an asynchronous function and returns the `[error, data]` tuple.\n\n** Parameters.\n- `asyncFn: (... .args: any[]) =\u003e Promise\u003cT\u003e` - the asynchronous function to execute\n- `defaultValue?: T` - optional, default value when an error occurs\n\n**Returns:**\n- `Promise\u003c[Error | null, T | undefined]\u003e` - tuple, the first element is the error (null on success), the second element is the data\n\n### `toSync\u003cT\u003e(fn, defaultValue?)` - the first element is the error (null on success), the second is the data\n\nSynchronized version of the `to` function for handling synchronized functions that may throw errors.\n\n**Arguments:**\n- `fn: () =\u003e T` - the synchronization function to be executed\n- `defaultValue?: T` - optional, default value when an error occurs\n\n**Returns:**\n- `[Error | null, T | undefined]` - the tuple\n\n### `toPromise\u003cT\u003e(promise, defaultValue?)`\n\nWraps the Promise instance directly.\n\n**Parameters:**\n- `promise: Promise\u003cT\u003e` - the Promise to be wrapped\n- `defaultValue?: T` - optionally, the default value when the Promise is rejected\n\n**Returns:**\n- `Promise\u003c[Error | null, T | undefined]\u003e` - The tuple\n\n## 💡 Usage Examples\n\n### 1. API call handling\n\n```typescript\nimport { to } from 'go-style-error';\n\nasync function loadUserProfile(userId: number) {\n  const [userError, user] = await to(() =\u003e fetchUser(userId));\n  const [postsError, posts] = await to(() =\u003e fetchUserPosts(userId), []);\n  const [settingsError, settings] = await to(\n    () =\u003e fetchUserSettings(userId),\n    { theme: 'light', notifications: false }\n  );\n\n  // We can continue to use the defaults even if something fails.\n  return {\n    user: user || { id: 0, name: 'Anonymous' },\n    posts: posts || [],\n    settings: settings || { theme: 'light', notifications: false }\n  };\n}\n\n### 2. JSON parsing\n\n```typescript\nimport { toSync } from 'go-style-error';\n\nfunction parseUserData(jsonString: string) {\n  const [error, userData] = toSync(() =\u003e JSON.parse(jsonString), {});\n  \n  if (error) {\n    console.error('Invalid JSON:', error.message);\n    return null;\n  }\n  \n  return userData;\n}\n\n### 3. Database operations\n\n```typescript\nimport { to } from 'go-style-error';\n\nasync function createUser(userData: UserData) {\n  const [validationError, validatedData] = await to(() =\u003e validateUser(userData));\n  if (validationError) {\n    return { success: false, error: validationError.message };\n  }\n\n  const [dbError, user] = await to(() =\u003e db.users.create(validatedData));\n  if (dbError) {\n    return { success: false, error: 'Failed to create user' };\n  }\n\n  return { success: true, user };\n}\n\n### 4. Documentation operations\n\n```typescript\nimport { toSync } from 'go-style-error';\nimport fs from 'fs';\n\nfunction readConfigFile(path: string) {\n  const [readError, content] = toSync(() =\u003e fs.readFileSync(path, 'utf8'));\n  if (readError) {\n    console.error('Failed to read config file:', readError.message);\n    return null;\n  }\n\n  const [parseError, config] = toSync(() =\u003e JSON.parse(content), {});\n  if (parseError) {\n    console.error('Invalid config format:', parseError.message);\n    return null;\n  }\n\n  return config;\n}\n\n### 5. network request\n\n```typescript\nimport { toPromise } from 'go-style-error';\n\nasync function fetchWithTimeout(url: string, timeout = 5000) {\n  const controller = new AbortController();\n  const timeoutId = setTimeout(() =\u003e controller.abort(), timeout);\n\n  const promise = fetch(url, { signal: controller.signal })\n    .then(res =\u003e res.json())\n    .finally(() =\u003e clearTimeout(timeoutId));\n\n  const [error, data] = await toPromise(promise, null);\n  \n  if (error) {\n    console.error('Request failed:', error.message);\n    return null;\n  }\n\n  return data;\n}\n\n## 🔧 Development\n\n### Install dependencies\n\n```bash \npnpm install \n```\n\n### Run tests\n\n```bash \npnpm test:watch \n```\n\n### Build the library\n\n```bash \npnpm build \n```\n\n### Code formatting\n\n```bash \npnpm format \n```\n\n### Type checking\n\n```bash \npnpm typecheck \n```\n\n## 🤝 贡献\n\n欢迎提交 Issue 和 Pull Request！\n\n## 📄 许可证\n\nMIT License\n\n## 🙏 致谢\n\nThis library was inspired by:\n- Go language's error handling model\n- [await-to-js](https://github.com/scopsy/await-to-js) Library\n- Community discussions on graceful error handling\n\n---\n\n** Makes asynchronous error handling simple and elegant! ** 🎉","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchenhaojie9527%2Fgo-style-error","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchenhaojie9527%2Fgo-style-error","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchenhaojie9527%2Fgo-style-error/lists"}