{"id":29850444,"url":"https://github.com/peterboyer/pb.safe","last_synced_at":"2026-06-25T08:32:08.925Z","repository":{"id":261202769,"uuid":"882978532","full_name":"peterboyer/pb.safe","owner":"peterboyer","description":"Errors as values; try/catch as a function.","archived":false,"fork":false,"pushed_at":"2025-02-27T10:28:28.000Z","size":166,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-20T06:35:43.038Z","etag":null,"topics":["error-handling","typescript"],"latest_commit_sha":null,"homepage":"https://npmjs.com/pb.safe","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/peterboyer.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":"2024-11-04T06:47:16.000Z","updated_at":"2025-05-21T13:29:47.000Z","dependencies_parsed_at":"2024-11-05T09:32:55.561Z","dependency_job_id":"12982668-c243-49b5-b2ad-9b4ffe4ea212","html_url":"https://github.com/peterboyer/pb.safe","commit_stats":null,"previous_names":["peterboyer/safe"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/peterboyer/pb.safe","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterboyer%2Fpb.safe","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterboyer%2Fpb.safe/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterboyer%2Fpb.safe/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterboyer%2Fpb.safe/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/peterboyer","download_url":"https://codeload.github.com/peterboyer/pb.safe/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterboyer%2Fpb.safe/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34767543,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-25T02:00:05.521Z","response_time":101,"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":["error-handling","typescript"],"created_at":"2025-07-29T20:40:11.294Z","updated_at":"2026-06-25T08:32:08.914Z","avatar_url":"https://github.com/peterboyer.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# safe\n\n## Installation\n\n```shell\nnpm install pb.safe\n```\n\n## Requirements\n\n- `typescript@\u003e=5.0.0`\n- `tsconfig.json \u003e \"compilerOptions\" \u003e { \"strict\": true }`\n\n# API\n\n- [`safe`](#safecallback)\n- [`unwrap`](#unwrapvalue)\n- [`ErrorADT`](#erroradt)\n\n### `safe(callback)`\n\nUse `safe` to execute a given `callback` function and return either its result\nvalue or any `Error` that it may have thrown. If a non-`Error` is thrown, a new\n`Error` will instantiated with the thrown value as its `cause`.\n\n\u003e `@description`\n\u003e\n\u003e Executes the given `callback` within a try/catch.\n\u003e - Returns thrown `Error` values as-is if it is an `instanceof` `Error`,\n\u003e - Returns thrown non-`Error` values as the `cause` of a new `Error` value.\n\u003e - Otherwise returns the result value as-is.\n\u003e\n\u003e If the return type of the `callback` is `unknown`, then the placeholder\n\u003e `Unknown` type is used instead to allow for a return type union containing\n\u003e `Error`.\n\n\n```ts\nimport { safe } from \"pb.safe\";\n\nconst value = safe(() =\u003e 0 / 0);\n//    ^ number | Error\n\nvoid function (): string | Error {\n  // handle error\n  if (value instanceof Error) {\n    return value;\n    //     ^ Error\n  }\n\n  // continue\n  return value.toString();\n  //     ^ number\n};\n```\n\n\n`Promise` return values are also supported.\n\n\n```ts\nconst value = safe(() =\u003e fetch(\"https://example.com/api/endpoint.json\"));\n//    ^ Promise\u003cResponse | Error\u003e\n```\n\n\n\u003cdetails\u003e\u003csummary\u003e(\u003cstrong\u003eExample\u003c/strong\u003e) Real-world example.\u003c/summary\u003e\n\n\n```ts\ntype Value = { id: string };\n\nvoid function getValue(): Value | undefined | Error {\n  const valueJson = window.localStorage.getItem(\"key\");\n  if (!valueJson) {\n    return undefined;\n  }\n\n  const valueUnknown = safe(() =\u003e JSON.parse(valueJson));\n  if (valueUnknown instanceof Error) {\n    return valueUnknown;\n  }\n\n  const value = safe(() =\u003e parseValueOrThrow(valueUnknown));\n  if (value instanceof Error) {\n    return value;\n  }\n\n  return value;\n};\n```\n\n\u003c/details\u003e\n\n\u003cdiv align=right\u003e\u003ca href=#api\u003eBack to top ⤴\u003c/a\u003e\u003c/div\u003e\n\n### `unwrap(value)`\n\nUse `unwrap` in cases where you either want a value or `undefined` if `Error`.\n\n\u003e `@description`\n\u003e\n\u003e - Returns `undefined` if the given `value` is an `instanceof` `Error`.\n\u003e - Otherwise returns the given `value` as is.\n\n\n```ts\nimport { unwrap } from \"pb.safe\";\n\nconst value = safe(() =\u003e 0 / 0);\n//    ^ number | Error\n\nconst valueOrUndefined = unwrap(value);\n//    ^ number | undefined\n```\n\n\n\u003cdiv align=right\u003e\u003ca href=#api\u003eBack to top ⤴\u003c/a\u003e\u003c/div\u003e\n\n### `ErrorADT`\n\n- type `ErrorADT\u003cTType\u003e`\n- value `ErrorADT(type, cause?)`\n\nUse `ErrorADT` to define `Error` objects with a typed \"type\" property\ninstead of sub-classing `Error`. The \"type\" can be used for handling different\n`Error` cases.\n\n\u003e `@description`\n\u003e\n\u003e Returns an extended `Error` type with an added `type` property to use as a\n\u003e discriminated union. If `undefined` is used as member of the `TType`\n\u003e parameter, then the `type` property becomes optional. This allows untyped\n\u003e `Error`s to be returned alongside `ErrorADT`s.\n\n\n```ts\nfunction getStoredValue(): string | undefined | ErrorADT\u003c\"Storage\"\u003e {\n  const response = safe(() =\u003e window.localStorage.getItem(\"key\"));\n  if (response instanceof Error) {\n    return ErrorADT(\"Storage\", response);\n  }\n  return response ?? undefined;\n}\n\nconst value = getStoredValue();\n//    ^ string | undefined | ErrorADT\u003c\"Storage\"\u003e\nif (value instanceof Error) {\n  //^ Error\u003c\"Storage\"\u003e\n  if (value.type === \"Storage\") {\n    //      ^ \"Storage\"\n  }\n}\n```\n\n\n\u003cdetails\u003e\u003csummary\u003e(\u003cstrong\u003eExample\u003c/strong\u003e) Request/Response to return a User record from a database.\u003c/summary\u003e\n\n```ts\nimport { ErrorADT } from \"pb.safe\";\n\ntype User = { id: string; name: string };\ntype AuthContext = { isAdmin: boolean };\n//prettier-ignore\n\nasync function getUser(\n  id: string,\n  authContext: AuthContext,\n): Promise\u003cUser | ErrorADT\u003c\"NotFound\" | \"NotAllowed\" | undefined\u003e\u003e {\n  if (!authContext.isAdmin) {\n    return ErrorADT(\"NotAllowed\");\n  }\n\n  const user = await safe(() =\u003e queryUserFromDatabase(id));\n  if (user instanceof Error) {\n    return user;\n  }\n\n  if (!user) {\n    return ErrorADT(\"NotFound\");\n  }\n\n  return user;\n}\n\nexport async function onRequest(\n  params: { id: string },\n  authContext: AuthContext,\n): Promise\u003cResponse\u003e {\n  const user = await getUser(params.id, authContext);\n  if (user instanceof Error) {\n    if (user.type === \"NotAllowed\") {\n      return Response.json({ error: user.type }, { status: 403 });\n    } else if (user.type === \"NotFound\") {\n      return Response.json({ error: user.type }, { status: 404 });\n    }\n    console.error(user);\n    return Response.json({ error: \"InternalServerError\" }, { status: 500 });\n  }\n  return Response.json({ ...user });\n}\n```\n\n\u003c/details\u003e\n\n\u003cdiv align=right\u003e\u003ca href=#api\u003eBack to top ⤴\u003c/a\u003e\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeterboyer%2Fpb.safe","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpeterboyer%2Fpb.safe","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeterboyer%2Fpb.safe/lists"}