Skip to content

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

Function: runCatching()

Call Signature

ts
function runCatching<T>(block): Result<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() => TThe block to run.

Returns

Result<T, unknown>

Example

ts
const result = runCatching(() => mightFail());

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

Call Signature

ts
function runCatching<T, C>(block, ...exceptions): Result<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() => TThe block to run.
...exceptionsCThe exception classes to catch.

Returns

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

Example

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

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