@wpkernel/pipeline / maybeTry
Function: maybeTry()
ts
function maybeTry<T>(run, onError): MaybePromise<T>;Runs an operation and recovers from either a synchronous throw or a rejected thenable.
A successful synchronous result is returned directly. A synchronous throw calls onError immediately, so a synchronous recovery also remains synchronous. Once run returns a thenable, the outcome is a native promise and recovery runs through its rejection channel. The recovery function may itself return a value or thenable.
Type Parameters
T
T
Parameters
run
() => MaybePromise<T>
Operation to execute.
onError
(error) => MaybePromise<T>
Recovery invoked with the original failure.
Returns
MaybePromise<T>
The successful result or recovery result, preserving sync when possible.
Example
ts
const parsed = maybeTry(
() => JSON.parse('{invalid}') as unknown,
() => ({ valid: false })
);