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.
deno add jsr:@synitio/trycatchJSR 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/trycatchNote: the JSR CLI creates a
.npmrcfile. Keep it in source control so future installs work.
import { tryCatch } from "@synitio/trycatch";
const [value, error] = tryCatch(() => JSON.parse("{\"ok\":true}"));
if (error) {
console.error(error.message);
} else {
console.log(value);
}import { tryCatch } from "@synitio/trycatch";
const [data, fetchError] = await tryCatch(fetch("https://example.com"));
if (fetchError) {
console.error(fetchError.message);
}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();
});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);
},
};tryCatch(operation)operationcan be a function, an async function, or a Promise.- Returns
[value, null]on success or[null, error]on failure.
This library is runtime-agnostic and works in Deno, Node.js, Bun, and Cloudflare Workers (ESM).
TryCatchResult<T, E>TryCatchSuccess<T>TryCatchFailure<E>StandardError(Errorwith optionalcause)
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.
MIT. See LICENSE.md.