Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

@dschz/try-catch

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@dschz/try-catch

Simple try-catch utility function for JavaScript

Source
npmnpm
Version
1.0.3
Version published
Weekly downloads
129
6350%
Maintainers
1
Weekly downloads
 
Created
Source

@dschz/try-catch

A tiny utility to wrap promises or async functions and return a [error, data] tuple — no more try/catch boilerplate.

✨ Features

  • ✅ Supports both async functions and raw promises
  • ✅ Catches both sync and async errors
  • ✅ Strongly typed result via Result<T, E>
  • ✅ Zero dependencies — just TypeScript

📆 Installation

npm install @dschz/try-catch
pnpm install @dschz/try-catch
yarn install @dschz/try-catch
bun install @dschz/try-catch

🚀 Usage

import { tryCatch } from "@dschz/try-catch";

const [err, data] = await tryCatch(fetch("/api/data"));

if (err) {
  console.error("Something went wrong:", err);
} else {
  console.log("Data:", data);
}

You can also pass a function that returns a promise:

const [err, user] = await tryCatch(() => fetchUserById(123));

🧠 Types

type Success<T> = [error: null, data: T];
type Failure<E extends Error = Error> = [error: E, data: null];
type Result<T, E extends Error = Error> = Success<T> | Failure<E>;

The return value is a tuple:

[error, data]; // One will always be null

🧪 Example with Custom Error Types

class MyError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "MyError";
  }
}

const [err, data] = await tryCatch<MyType, MyError>(() => doSomething());

📄 License

MIT © @dschz

FAQs

Package last updated on 12 May 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts