{"id":29420779,"url":"https://github.com/marian1309/try-catch","last_synced_at":"2025-07-12T02:44:46.025Z","repository":{"id":299663333,"uuid":"1003736042","full_name":"Marian1309/try-catch","owner":"Marian1309","description":"🔒 Type-safe try/catch wrapper ⚙️ for async operations ⚡️","archived":false,"fork":false,"pushed_at":"2025-06-19T14:06:13.000Z","size":24,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-06T04:17:31.794Z","etag":null,"topics":["error-handling","try-catch","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@pidchashyi/try-catch","language":"TypeScript","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/Marian1309.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}},"created_at":"2025-06-17T15:31:55.000Z","updated_at":"2025-06-28T13:04:45.000Z","dependencies_parsed_at":"2025-06-17T17:53:28.697Z","dependency_job_id":null,"html_url":"https://github.com/Marian1309/try-catch","commit_stats":null,"previous_names":["marian1309/try-catch"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Marian1309/try-catch","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marian1309%2Ftry-catch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marian1309%2Ftry-catch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marian1309%2Ftry-catch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marian1309%2Ftry-catch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Marian1309","download_url":"https://codeload.github.com/Marian1309/try-catch/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marian1309%2Ftry-catch/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":264926332,"owners_count":23684320,"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":["error-handling","try-catch","typescript"],"created_at":"2025-07-12T02:44:44.079Z","updated_at":"2025-07-12T02:44:46.014Z","avatar_url":"https://github.com/Marian1309.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# `@pidchashyi/try-catch`\n\n\u003e 🧰 Type-safe `try/catch` wrapper for async operations — returns structured `Result\u003cT, E\u003e` objects instead of throwing errors.\n\nEliminate unhandled exceptions and simplify async error handling with a clean, typed interface. Features optional logging, lifecycle hooks, retry mechanisms, performance tracking, and full type inference.\n\n---\n\n## 📦 Installation\n\n```bash\nnpm install @pidchashyi/try-catch\n```\n\n---\n\n## ⚙️ Core Types\n\n### `Result\u003cT, E\u003e`\n\n```ts\ntype Result\u003cT, E = Error\u003e = Success\u003cT\u003e | Failure\u003cE\u003e;\n```\n\n#### Success Type\n\n```ts\ntype Success\u003cT\u003e = {\n  status: \"success\"; // Always \"success\"\n  data: T; // The successful result data\n  error: null; // Always null\n  performance?: number; // Execution time in seconds (if enabled)\n};\n```\n\n#### Failure Type\n\n```ts\ntype Failure\u003cE\u003e = {\n  status: \"failure\"; // Always \"failure\"\n  data: null; // Always null\n  error: E; // The error that occurred\n  performance?: number; // Execution time in seconds (if enabled)\n};\n```\n\n### Configuration Types\n\n#### RetryOptions\n\n```ts\ntype RetryOptions = {\n  retries: number; // Number of retry attempts\n  delayMs?: number; // Delay between retries in milliseconds\n};\n```\n\n#### BaseTryCatchOptions\n\n```ts\ntype BaseTryCatchOptions\u003cE = Error\u003e = {\n  logError?: boolean; // Enable error logging to console\n  onError?: (error: E) =\u003e void; // Custom error handler callback\n  onFinally?: () =\u003e void; // Callback executed after try-catch\n  performance?: boolean; // Enable performance tracking in seconds\n};\n```\n\n#### TryCatchOptions\n\n```ts\ntype TryCatchOptions\u003cE = Error\u003e = BaseTryCatchOptions\u003cE\u003e \u0026 {\n  retry?: RetryOptions;\n};\n```\n\n#### TryCatchAllOptions\n\n```ts\ntype TryCatchAllOptions\u003cE = Error\u003e = BaseTryCatchOptions\u003cE\u003e \u0026 {\n  failFast?: boolean; // If true, fails on first error (default)\n};\n```\n\n#### PartialResults\n\n```ts\ntype PartialResults\u003cT, E = Error\u003e = {\n  successes: T[]; // Array of successful results\n  errors: E[]; // Array of errors that occurred\n  successIndices: number[]; // Original indices of successes\n  errorIndices: number[]; // Original indices of failures\n};\n```\n\n---\n\n## 🌍 Global Configuration\n\nThe package provides utilities to set global configuration options that will be applied to all try-catch operations. Local options passed to individual try-catch calls will override these global settings.\n\n### Global Configuration Functions\n\n```ts\nsetGlobalTryCatchConfig(config: Partial\u003cTryCatchOptions\u003e): void\ngetGlobalTryCatchConfig(): Partial\u003cTryCatchOptions\u003e\n```\n\n### Example: Setting Global Error Handling\n\n```ts\n// @/app/layout.tsx\nimport { setGlobalTryCatchConfig } from \"@pidchashyi/try-catch\";\n\n// Set up global error tracking for all try-catch operations\nsetGlobalTryCatchConfig({\n  logError: true,\n  performance: true,\n  onError: async (error) =\u003e {\n    await trackError({\n      message: \"Unhandled tryCatch error\",\n      source: \"global\",\n      error,\n    });\n  },\n});\n\n// All subsequent try-catch calls will use these settings\nconst result1 = await tryCatch(fetchData()); // Uses global config\nconst result2 = await tryCatchSync(processData); // Uses global config\n\n// Local options override global settings\nconst result3 = await tryCatch(fetchData(), {\n  logError: false, // Overrides global logError setting\n  onError: (err) =\u003e customErrorHandler(err), // Overrides global onError handler\n});\n```\n\n### Available Global Options\n\nThe global configuration accepts all standard try-catch options:\n\n```ts\ntype TryCatchOptions\u003cE = Error\u003e = {\n  logError?: boolean; // Enable error logging to console\n  onError?: (error: E) =\u003e void; // Global error handler\n  onFinally?: () =\u003e void; // Global cleanup function\n  performance?: boolean; // Enable performance tracking\n  retry?: {\n    // Global retry settings\n    retries: number;\n    delayMs?: number;\n  };\n};\n```\n\n### Best Practices\n\n- Set global configuration early in your application's lifecycle\n- Use global config for common error tracking/logging\n- Override global settings with local options when needed\n- Keep global handlers lightweight to avoid performance impact\n- Consider using TypeScript for better type inference\n\n---\n\n## 🛠️ Core Functions\n\n### `tryCatchSync\u003cT, S = T, E = Error\u003e`\n\nSynchronous try-catch wrapper for non-async operations.\n\n```ts\nconst result = tryCatchSync(() =\u003e someOperation(), {\n  select: (data) =\u003e transformData(data),\n  logError: true,\n  onError: (err) =\u003e handleError(err),\n  onFinally: () =\u003e cleanup(),\n});\n```\n\n### `tryCatch\u003cT, S = T, E = Error\u003e`\n\nAsynchronous try-catch wrapper with retry capabilities.\n\n```ts\nconst result = await tryCatch(fetchData(), {\n  retry: { retries: 3, delayMs: 1000 },\n  select: (data) =\u003e transformData(data),\n  logError: true,\n  onError: (err) =\u003e handleError(err),\n  onFinally: () =\u003e cleanup(),\n});\n```\n\n### `tryCatchAll\u003cT, E = Error\u003e`\n\nExecute multiple promises concurrently with fail-fast behavior.\n\n```ts\nconst result = await tryCatchAll([promise1, promise2, promise3], {\n  logError: true,\n  onError: (err) =\u003e handleError(err),\n  onFinally: () =\u003e cleanup(),\n});\n```\n\n### `tryCatchAllSafe\u003cT, E = Error\u003e`\n\nExecute multiple promises concurrently with fail-soft behavior.\n\n```ts\nconst result = await tryCatchAllSafe([promise1, promise2, promise3], {\n  logError: true,\n  onError: (err) =\u003e handleError(err),\n  onFinally: () =\u003e cleanup(),\n});\n```\n\n---\n\n## 🔍 Utility Functions\n\n### Type Guards\n\n```ts\nisSuccess\u003cT, E\u003e(result: Result\u003cT, E\u003e): result is Success\u003cT\u003e\nisFailure\u003cT, E\u003e(result: Result\u003cT, E\u003e): result is Failure\u003cE\u003e\n```\n\n### Helper Functions\n\n```ts\nsleep(ms: number): Promise\u003cvoid\u003e                 // Delay execution\ntoError(error: unknown): Error                   // Convert unknown to Error\ngetErrorMessage(error: unknown): string          // Extract error message\nmap\u003cT, U, E\u003e(result: Result\u003cT, E\u003e, fn: (value: T) =\u003e U): Result\u003cU, E\u003e  // Transform success value\n```\n\n---\n\n## 📝 Examples\n\n### Basic Usage with Performance Tracking\n\n```ts\nimport { tryCatch, isSuccess } from \"@pidchashyi/try-catch\";\n\nconst result = await tryCatch(\n  fetch(\"https://api.example.com/data\").then((res) =\u003e res.json()),\n  {\n    select: (data) =\u003e data.items,\n    logError: true,\n    performance: true, // Enable performance tracking\n  }\n);\n\nif (isSuccess(result)) {\n  console.log(\"Data:\", result.data);\n  console.log(\"Operation took:\", result.performance, \"seconds\");\n} else {\n  console.error(\"Error:\", result.error);\n  console.log(\"Failed operation took:\", result.performance, \"seconds\");\n}\n```\n\n### With Retry Logic and Performance Tracking\n\n```ts\nconst result = await tryCatch(fetchWithPotentialFailure(), {\n  retry: {\n    retries: 3,\n    delayMs: 1000,\n  },\n  logError: true,\n  onError: (err) =\u003e notifyUser(err),\n  performance: true, // Enable performance tracking\n});\n\nif (isSuccess(result)) {\n  console.log(`Operation succeeded in ${result.performance} seconds`);\n}\n```\n\n### Parallel Operations\n\n```ts\nconst result = await tryCatchAll([fetchUser(1), fetchUser(2), fetchUser(3)]);\n\nif (isSuccess(result)) {\n  console.log(\"All users:\", result.data);\n}\n```\n\n### Safe Parallel Operations\n\n```ts\nconst result = await tryCatchAllSafe([\n  fetchUser(1),\n  fetchUser(2),\n  fetchUser(3),\n]);\n\nif (isSuccess(result)) {\n  console.log(\"Successful fetches:\", result.data.successes);\n  console.log(\"Failed fetches:\", result.data.errors);\n  console.log(\"Success indices:\", result.data.successIndices);\n}\n```\n\n---\n\n## 🛡️ Features \u0026 Benefits\n\n✅ Fully typed `Success\u003cT\u003e` / `Failure\u003cE\u003e` results\n✅ Comprehensive retry mechanism\n✅ Performance tracking\n✅ Parallel execution support\n✅ Safe error handling with type inference\n✅ Optional logging and lifecycle hooks\n✅ Transform results with selectors\n✅ No dependencies\n✅ Framework agnostic\n\n---\n\n## 👤 Author\n\nBuilt with safety-first philosophy by [Pidchashyi](https://github.com/Marian1309/try-catch)\n\n---\n\n## 📄 License\n\nMIT © [LICENSE](https://github.com/Marian1309/try-catch/blob/main/LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarian1309%2Ftry-catch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmarian1309%2Ftry-catch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarian1309%2Ftry-catch/lists"}