trycatch: Type-Safe Error Handling for JavaScript & TypeScript

Jul 23, 2025

2 min read

title image

Error handling in JavaScript and TypeScript often relies on the classic try/catch block. While this works, it can be verbose, repetitive, and error-prone—especially when dealing with asynchronous code. Inspired by Go's approach to error handling, I created trycatch: a type-safe, minimal, and ergonomic wrapper for try/catch in JavaScript and TypeScript.

Why trycatch?

Installation

# With bun
bun add @pr0gstar/trycatch-wrapper
 
# With npm
npm install @pr0gstar/trycatch-wrapper
 
# With yarn
yarn add @pr0gstar/trycatch-wrapper

Basic Usage

The trycatch package provides a simple API for wrapping code blocks and promises:

import { tryCatch } from "@pr0gstar/trycatch-wrapper";
 
const [data, error] = await tryCatch(async () => {
  // Your async code here
  return await fetchData();
});
 
if (error) {
  // Handle error
  console.error(error);
} else {
  // Use data
  console.log(data);
}

Real Example from This Project

In this project, tryCatch is used to handle errors when loading blog posts and other async operations. For example, in the loader for the writings page:

import { tryCatch } from "@pr0gstar/trycatch-wrapper";
import { getPosts } from "~/utils/mdx.server";
 
export const loader = async () => {
  const { data: posts, error } = await tryCatch(getPosts());
  if (error) {
    console.error("Error loading posts:", error);
    throw new Response("Posts not found!", { status: 404 });
  }
  return { posts };
};

This approach makes error handling concise and type-safe, reducing boilerplate and improving code clarity.

Conclusion

The trycatch npm package is a small but powerful tool for modern JavaScript and TypeScript projects. It helps you write safer, cleaner, and more maintainable code by making error handling explicit and ergonomic. If you want to improve your error handling, give trycatch a try!