{"id":10613,"library":"catch-unknown","title":"Type-Safe Catch Blocks","description":"catch-unknown is a focused utility library designed to simplify the handling of `unknown` error types within JavaScript and TypeScript `catch` blocks. Following TypeScript 4.4's decision to default `catch` variables to `unknown`, developers are required to perform explicit type guarding or conversion. This library provides two primary functions: `isError`, which functions as a type guard to verify if a value conforms to the standard `Error` interface, and `asError`, which transforms any thrown value into an `Error`-like object, guaranteeing it possesses at least `name` and `message` properties. Currently at version `2.0.0`, the library emphasizes stability, minimal footprint, compiles to ES6 for broad compatibility, and has no runtime dependencies, ensuring a small package size and efficient error handling without introducing complex abstractions.","status":"active","version":"2.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/trevorr/catch-unknown","tags":["javascript","base62","id","random","uuid","typescript"],"install":[{"cmd":"npm install catch-unknown","lang":"bash","label":"npm"},{"cmd":"yarn add catch-unknown","lang":"bash","label":"yarn"},{"cmd":"pnpm add catch-unknown","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Used to convert any thrown value into an object conforming to the standard Error interface for consistent error handling. The CommonJS `require` syntax is a common pitfall in modern ESM-first environments.","wrong":"const asError = require('catch-unknown').asError;","symbol":"asError","correct":"import { asError } from 'catch-unknown';"},{"note":"A TypeScript type guard function that asserts whether a value is an instance of the Error interface. Similar to `asError`, be mindful of module import syntax in different environments.","wrong":"const isError = require('catch-unknown').isError;","symbol":"isError","correct":"import { isError } from 'catch-unknown';"}],"quickstart":{"code":"import { asError } from 'catch-unknown';\n\n// A dummy logger for demonstration purposes\nconst logger = {\n  warn: (message: string) => console.warn(`[WARN] ${message}`),\n  error: (message: string) => console.error(`[ERROR] ${message}`)\n};\n\nasync function performRiskyOperation() {\n  return new Promise((resolve, reject) => {\n    // Simulate an error or non-Error throw\n    const rand = Math.random();\n    if (rand < 0.3) {\n      reject(new Error('Standard error occurred'));\n    } else if (rand < 0.6) {\n      reject('A simple string was thrown');\n    } else {\n      reject({ code: 500, detail: 'An unexpected object was thrown' });\n    }\n  });\n}\n\nasync function runExample() {\n  try {\n    await performRiskyOperation();\n    console.log('Operation successful!');\n  } catch (err) {\n    // Use asError to safely log the error message regardless of what was thrown\n    const errorObject = asError(err);\n    logger.warn(`Operation failed: ${errorObject.message}`);\n    \n    // Rethrow the original error if necessary\n    throw err;\n  }\n}\n\nrunExample().catch(finalErr => {\n  logger.error(`Application level error caught: ${asError(finalErr).message}`);\n});","lang":"typescript","description":"Demonstrates using `asError` within an asynchronous `try...catch` block to safely extract a message from any thrown value (Error, string, object) and log it, then rethrow the original."},"warnings":[{"fix":"Integrate `catch-unknown` by using `isError(err)` as a type guard (`if (isError(err)) { ... }`) or `asError(err)` to convert the `unknown` value into an `Error`-like object before attempting to access its properties (e.g., `asError(err).message`).","message":"TypeScript versions 4.4 and above default `catch` block variables to `unknown` type when `useUnknownInCatchVariables` is enabled (implicitly by `strict` mode or explicitly). This change means you cannot directly access properties like `.message` or `.name` on a caught `err` without explicit type narrowing or conversion, leading to TypeScript errors.","severity":"gotcha","affected_versions":"TypeScript >=4.4"}],"env_vars":null,"search_vec":"'2.0.0':98 '4.4':31 'abstract':128 'aserror':75 'base62':130 'block':5,28 'broad':109 'catch':4,7,27,36 'catch-unknown':6 'compat':110 'compil':105 'complex':127 'conform':68 'convers':49 'current':95 'decis':33 'default':35 'depend':115 'design':14 'develop':40 'effici':122 'emphas':101 'ensur':116 'error':21,72,83,123 'es6':107 'explicit':45 'focus':11 'follow':29 'footprint':104 'function':55,58 'guarante':86 'guard':47,62 'handl':18,124 'id':131 'interfac':73 'introduc':126 'iserror':56 'javascript':24,129 'least':90 'librari':13,51,100 'like':84 'messag':93 'minim':103 'name':91 'object':85 'packag':119 'perform':44 'possess':88 'primari':54 'properti':94 'provid':52 'random':132 'requir':42 'runtim':114 'safe':3 'simplifi':16 'size':120 'small':118 'stabil':102 'standard':71 'thrown':79 'transform':77 'two':53 'type':2,22,46,61 'type-saf':1 'typescript':26,30,134 'unknown':8,20,39 'util':12 'uuid':133 'valu':67,80 'variabl':37 'verifi':64 'version':97 'within':23 'without':125","created_at":"2026-04-19T13:33:43.133207+00:00","updated_at":"2026-04-19T13:33:43.133207+00:00","problems":[{"fix":"Use `catch-unknown`'s `isError` type guard (`if (isError(err)) { ... }`) or convert the error using `asError(err)` before accessing properties (e.g., `asError(err).message`). Ensure your `tsconfig.json` has `useUnknownInCatchVariables` enabled.","cause":"Attempting to access properties (e.g., `.message`, `.name`) directly on a `catch` variable typed as `unknown` without prior type narrowing or conversion. This is the default behavior for `catch` variables in TypeScript 4.4 and newer when `useUnknownInCatchVariables` is active.","error":"Property 'message' does not exist on type 'unknown'."},{"fix":"Ensure you are using named imports for `asError` and `isError`: `import { asError } from 'catch-unknown';`. If using CommonJS, correctly destructure the named export: `const { asError } = require('catch-unknown');`.","cause":"This error typically indicates a CommonJS/ESM module interop issue where a named export is incorrectly imported as a default, or a bundler misinterprets the module format when transpiling.","error":"TypeError: (0, catch_unknown_1.asError) is not a function"},{"fix":"Install the package via your package manager: `npm install catch-unknown` or `yarn add catch-unknown`. If the problem persists in a TypeScript project, verify your `tsconfig.json` `types` or `typeRoots` settings, although this is uncommon for well-maintained packages.","cause":"The package is not installed in the project, or TypeScript cannot locate its declaration files (`.d.ts`), which are essential for type checking.","error":"Cannot find module 'catch-unknown' or its corresponding type declarations."}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/trevorr/catch-unknown","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/catch-unknown","openapi_spec":null,"status_page":null,"smithery":null,"categories":["testing"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}