Skip to content

tryCatch

function tryCatch<T, E>(promise): Promise<Result<T, E>>;

Defined in: try-catch.ts:68

Convert a promise (or function) into a tuple result: [data, error].

This is handy when you want to avoid try/catch at the call site.

Sync/async adaptive: a promise input or async function returns a Promise<Result>; a sync function returns the Result tuple directly — no await needed (and await still works on both).

Type Parameter Default type
T -
E Error
Parameter Type
promise PromiseLike<T>

Promise<Result<T, E>>

With a promise

const [user, error] = await tryCatch(fetch("/api/me").then((r) => r.json()));
if (error) {
// handle error
} else {
// use user
}

With a sync function — result is immediate

const [value, error] = tryCatch(() => JSON.parse('{"ok":true}')); // no await

With an async function (captures sync throws too)

const [data, error] = await tryCatch(async () => {
if (Math.random() > 0.5) {
throw new Error("boom");
}
return 123;
});
if (!error) {
// data === 123
}
function tryCatch<R, E>(fn): TryCatchReturn<R, E>;

Defined in: try-catch.ts:69

Convert a promise (or function) into a tuple result: [data, error].

This is handy when you want to avoid try/catch at the call site.

Sync/async adaptive: a promise input or async function returns a Promise<Result>; a sync function returns the Result tuple directly — no await needed (and await still works on both).

Type Parameter Default type
R -
E Error
Parameter Type
fn () => R

TryCatchReturn<R, E>

With a promise

const [user, error] = await tryCatch(fetch("/api/me").then((r) => r.json()));
if (error) {
// handle error
} else {
// use user
}

With a sync function — result is immediate

const [value, error] = tryCatch(() => JSON.parse('{"ok":true}')); // no await

With an async function (captures sync throws too)

const [data, error] = await tryCatch(async () => {
if (Math.random() > 0.5) {
throw new Error("boom");
}
return 123;
});
if (!error) {
// data === 123
}
function tryCatch<T, E>(input): MaybePromise<Result<T, E>>;

Defined in: try-catch.ts:70

Convert a promise (or function) into a tuple result: [data, error].

This is handy when you want to avoid try/catch at the call site.

Sync/async adaptive: a promise input or async function returns a Promise<Result>; a sync function returns the Result tuple directly — no await needed (and await still works on both).

Type Parameter Default type
T -
E Error
Parameter Type
input | PromiseLike<T> | (() => MaybePromise<T>)

MaybePromise<Result<T, E>>

With a promise

const [user, error] = await tryCatch(fetch("/api/me").then((r) => r.json()));
if (error) {
// handle error
} else {
// use user
}

With a sync function — result is immediate

const [value, error] = tryCatch(() => JSON.parse('{"ok":true}')); // no await

With an async function (captures sync throws too)

const [data, error] = await tryCatch(async () => {
if (Math.random() > 0.5) {
throw new Error("boom");
}
return 123;
});
if (!error) {
// data === 123
}