Skip to main content

runResult

@ts-rust/std


@ts-rust/std / Result / runResult

Function: runResult()

function runResult<T, E>(getResult): Result<T, E>;

Defined in: packages/std/src/result/result.ts:279

Safely executes an action that returns a Result, capturing thrown synchronous errors as an Err variant.

The runResult function executes the provided resultAction function, which returns a Result<T, E>. If the action succeeds, it returns the Result as-is (either Ok<T> or Err<E>). If the action throws an error, it is captured and wrapped in an Err variant returning UnexpectedError with a ResultErrorKind.Unexpected kind.

This function is useful for safely running synchronous Result-producing actions, if you are not 100% sure that the action will not throw an error, ensuring that any thrown errors are converted into an Err variant in a type-safe way.

Type Parameters

Type Parameter

T

E

Parameters

ParameterTypeDescription

getResult

() => Result<T, E>

A function that returns a Result<T, E>.

Returns

Result<T, E>

A Result<T, E> containing either the original Result from resultAction or an Err<E> if the action throws an error.

Example

import { runResult, ok, err } from "@ts-rust/std";

// Successful Result
const success = runResult(() => ok(42));
console.log(success.unwrap()); // 42

// Failed Result
const failure = runResult(() => err(new Error("Already failed")));
// "Expected error occurred: Error: Already failed"
console.log(failure.unwrapErr().expected?.message);

// Action throws an error
const thrown = runResult(() => {
throw new Error("Oops");
});
// "Unexpected error occurred: ResultError: [Unexpected] `runResult`: result action threw an exception. Reason: Error: Oops"
console.log(thrown.unwrapErr().unexpected?.message);