API reference / @evolu/common / Result / trySync
Function: trySync()
function trySync<T, E>(fn, mapError): Result<T, E>;
Defined in: packages/common/src/Result.ts:521
Wraps synchronous functions that may throw exceptions, returning a Result.
The trySync function is designed to handle synchronous code safely by
wrapping the execution in a try-catch block. If the function succeeds, it
returns an Ok result. If an exception is thrown, it maps the error to a
custom type and returns an Err result.
Example
interface ParseJsonError {
readonly type: "ParseJsonError";
readonly message: string;
}
const parseJson = (value: string): Result<unknown, ParseJsonError> =>
trySync(
() => JSON.parse(value) as unknown,
(error): ParseJsonError => ({
type: "ParseJsonError",
message: String(error),
}),
);
Type Parameters
| Type Parameter |
|---|
T |
E |
Parameters
| Parameter | Type |
|---|---|
fn | () => T |
mapError | (error) => E |
Returns
Result<T, E>