Wraps a function in a try-catch block to safely execute it and returns a Result.
try-catch
The type of the success value.
A string literal type for the error label.
The function to execute safely.
The error label to use if the function throws an error.
A Result containing either the success value or a structured error.
const [error, value] = safe(() => JSON.parse('{"foo": "bar"}'), 'json_parse_error');if (error) { console.error(error.source);} else { console.log(value);} Copy
const [error, value] = safe(() => JSON.parse('{"foo": "bar"}'), 'json_parse_error');if (error) { console.error(error.source);} else { console.log(value);}
Wraps a function in a
try-catch
block to safely execute it and returns a Result.