Skip to content

API reference / @backpack/error-handling / result / runCatchingAsync

Function: runCatchingAsync()

Call Signature

ts
function runCatchingAsync<T>(block): Promise<Result<Awaited<T>, unknown>>;

Runs the given callback, catching any exception, and wrapping its result in a Result object.

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
block() => T | Promise<T>The block to run.

Returns

Promise<Result<Awaited<T>, unknown>>

Example

ts
const result = await runCatchingAsync(() => mightFail());

if (result.failed) {
  const error = result.error;
  //    ^ inferred as `unknown`
}

Call Signature

ts
function runCatchingAsync<T, C>(block, ...exceptions): Promise<Result<Awaited<T>, C extends Class<E>[] ? E : unknown>>;

Runs the given callback, catching only the exceptions provided, and wrapping its result in a Result object.

Type Parameters

Type Parameter
T
C extends Class[]

Parameters

ParameterTypeDescription
block() => T | Promise<T>The block to run.
...exceptionsCThe exception classes to catch.

Returns

Promise<Result<Awaited<T>, C extends Class<E>[] ? E : unknown>>

Example

ts
const result = await runCatchingAsync(
  () => mightFail(),
  MyCustomError,
  MyOtherError,
);

if (result.failed) {
  const error = result.error;
  //    ^ inferred as `MyCustomError | MyOtherError`
}