utility function for catching errors, it aims to replace try-catch blocks.

with try and catch

try {
  const user = await getUser();
} catch (error) {
  // handle the error
}

with tryCatch:

the return type is a tuple: either [error, undefined] or [undefined, data]. This enforces type safety by requiring you to handle potential errors before accessing the data.

const [error, data] = await tryCatch(getUser());

if (error) {
  // handle the error
}

// data is the user object
data.name;

Installation

pnpm dlx shadcn@latest add https://mhl5.vercel.app/r/tryCatch.json

Usage

tryCatch

type User = {
  name: string;
};

type Error = {
  errorMessage: string;
};

const [error, user] = tryCatch<User, Error>(getUser());

if (error) {
  // handle the error
  console.log(error.errorMessage);
}

user.name;

tryCatchSync

const [error, data] = tryCatchSync(new Intl.NumberFormat(locale).format(count));