run
@ts-rust/std / Result / run
Function: run()
function run<T, E>(action, mkErr): Result<T, E>;
Defined in: packages/std/src/result/result.ts:159
Executes a synchronous action and wraps the outcome in a Result, handling errors with a custom error mapper.
The run function attempts to execute the provided action
function,
which returns a value of type T
. If the action succeeds, it returns an
Ok variant containing the result. If the action fails (throws an error),
the error is passed to the mkErr
function to create an error of type E
,
which is then wrapped in an Err variant.
This function is useful for safely executing operations that might fail, ensuring errors are handled in a type-safe way using the Result type.
Type Parameters
Type Parameter |
---|
|
|
Parameters
Parameter | Type | Description |
---|---|---|
| () => | A function that performs the operation, returning a value of type |
| ( | A function that converts an error (of type |
Returns
Result
<T
, E
>
A Result<T, E>
containing either the successful result (Ok<T>
) or the mapped error (Err<E>
).
Example
import { run, Result } from "@ts-rust/std";
const result: Result<{ key: string }, Error> = run(
(): { key: string } => JSON.parse('{ key: "value" }'),
(e) => new Error(`Operation failed: ${JSON.stringify(e)}`),
);
if (result.isOk()) {
console.log(result.unwrap()); // { key: "value" }
}