Skip to content

Function tryCatch

Package: @litert/utils-flow-controlSource: packages/partials/flow-control/src/Functions/TryCatch.ts

An expression-style try-catch[-finally] statement. Instead of the try { ... } catch { ... } syntax (which cannot be used as an expression), tryCatch wraps the same logic as a function call and returns the resulting value. It correctly handles all combinations of synchronous and asynchronous try, catch, and finally bodies — and automatically returns a Promise if any of the involved functions is asynchronous.


Import

ts
import { tryCatch } from '@litert/utils-flow-control';

Signature

ts
function tryCatch<TOk, TErr = never, TFinal extends void | Promise<void> = void>(
    opts: ITryCatchOptions<TOk, TErr, TFinal>
): ITryCatchResult<TOk, TErr, TFinal>;

Parameters

ParameterTypeDescription
optsITryCatchOptions<TOk, TErr, TFinal>Options object with try, catch, and optional finally bodies. See ITryCatchOptions

Return Value

The return value of the try body, or the return value of the catch body if an error was thrown. If any body is asynchronous, a Promise is returned automatically.


Error Handling

If the catch body or finally body throws, the error propagates to the caller normally, just as in a standard try-catch-finally statement.


Examples

ts
import { tryCatch } from '@litert/utils-flow-control';

// Synchronous
const result = tryCatch({
    try: () => JSON.parse('{"ok":true}'),
    catch: () => ({ ok: false }),
});
console.log(result); // { ok: true }

// Asynchronous
const data = await tryCatch({
    try: async () => fetch('/api/data').then(r => r.json()),
    catch: (e) => { console.error(e); return null; },
    finally: () => { console.log('done'); },
});