Skip to content

synit-io/tryCatch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tryCatch

A tiny helper that wraps sync or async operations and returns a tuple [value, error] instead of throwing.

Maintained by synit.io. Open-source contributions are welcome.

Install

Deno

deno add jsr:@synitio/trycatch

Node.js / Bun / Cloudflare Workers

JSR packages are ESM-only. For Node.js, set "type": "module" in package.json.

Use a package manager that supports JSR, or the JSR CLI:

pnpm add jsr:@synitio/trycatch # pnpm 10.9+
yarn add jsr:@synitio/trycatch # yarn 4.9+
npx jsr add @synitio/trycatch
bunx jsr add @synitio/trycatch

Note: the JSR CLI creates a .npmrc file. Keep it in source control so future installs work.

Usage

Basic (sync)

import { tryCatch } from "@synitio/trycatch";

const [value, error] = tryCatch(() => JSON.parse("{\"ok\":true}"));
if (error) {
  console.error(error.message);
} else {
  console.log(value);
}

Promise (async)

import { tryCatch } from "@synitio/trycatch";

const [data, fetchError] = await tryCatch(fetch("https://example.com"));
if (fetchError) {
  console.error(fetchError.message);
}

Async function

import { tryCatch } from "@synitio/trycatch";

const [payload, payloadError] = await tryCatch(async () => {
  const res = await fetch("https://example.com/api");
  if (!res.ok) throw new Error("Request failed");
  return res.json();
});

Cloudflare Workers

import { tryCatch } from "@synitio/trycatch";

export default {
  async fetch(): Promise<Response> {
    const [value, error] = await tryCatch(Promise.resolve("hello"));
    if (error) return new Response(error.message, { status: 500 });
    return new Response(value);
  },
};

API

tryCatch(operation)
  • operation can be a function, an async function, or a Promise.
  • Returns [value, null] on success or [null, error] on failure.

Runtime compatibility

This library is runtime-agnostic and works in Deno, Node.js, Bun, and Cloudflare Workers (ESM).

Types

  • TryCatchResult<T, E>
  • TryCatchSuccess<T>
  • TryCatchFailure<E>
  • StandardError (Error with optional cause)

Error normalization

If a non-Error value is thrown or rejected, tryCatch returns a new Error("Operation failed with a non-error value.") and assigns the original value to error.cause.

License

MIT. See LICENSE.md.

About

A tiny helper that wraps sync or async operations and returns a tuple `[value, error]` instead of throwing.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors