Runs a function that may raise an exception, trapping it. Returns an Ok
with
the return value of the function, if it has finished successfully, or an Error
with the raised exception.
This API is still experimental, so it may change or be removed in future versions. You should not rely on it for production applications.
Runs a function that may raise an exception, trapping it. Returns an Ok
with
the return value of the function, if it has finished successfully, or an Error
with the raised exception.
function successor(natural) {
if (natural < 0) {
throw `Not a natural number: ${natural}`;
} else {
return natural + 1;
}
}
const Result = require('folktale/result');
Result.try(() => successor(-1));
// ==> Result.Error('Not a natural number: -1')
Result.try(() => successor(1));
// ==> Result.Ok(2)
(f) => {
try {
return Ok(f());
} catch (e) {
return Error(e);
}
}