Type-Safe Catch Blocks

2.0.0 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import { asError } from 'catch-unknown';

// A dummy logger for demonstration purposes
const logger = {
  warn: (message: string) => console.warn(`[WARN] ${message}`),
  error: (message: string) => console.error(`[ERROR] ${message}`)
};

async function performRiskyOperation() {
  return new Promise((resolve, reject) => {
    // Simulate an error or non-Error throw
    const rand = Math.random();
    if (rand < 0.3) {
      reject(new Error('Standard error occurred'));
    } else if (rand < 0.6) {
      reject('A simple string was thrown');
    } else {
      reject({ code: 500, detail: 'An unexpected object was thrown' });
    }
  });
}

async function runExample() {
  try {
    await performRiskyOperation();
    console.log('Operation successful!');
  } catch (err) {
    // Use asError to safely log the error message regardless of what was thrown
    const errorObject = asError(err);
    logger.warn(`Operation failed: ${errorObject.message}`);
    
    // Rethrow the original error if necessary
    throw err;
  }
}

runExample().catch(finalErr => {
  logger.error(`Application level error caught: ${asError(finalErr).message}`);
});

view raw JSON →