{"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,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","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"}