The function which may throw, which will be wrapped.
Transform a function which may throw an error into one with an identical call signature except that it will return a instead of throwing an error.
This allows you to handle the error locally with all the normal Result
tools
rather than having to catch an exception. Where the tryOr
and
tryOrElse
functions are useful for a single call, this is useful
to make a new version of a function to be used repeatedly.
This overload allows you to transform the error immediately, using the second argument.
The JSON.parse
method will throw if the string passed to it is invalid. You
can use this safe
method to transform it into a form which will not throw,
wrapping it in a custom error :
import { safe } from 'true-myth/task';
class ParsingError extends Error {
name = 'ParsingError';
constructor(error: unknown) {
super('Parsing error.', { cause: error });
}
}
const parse = safe(JSON.parse, (error) => {
return new ParsingError(error);
});
let result = parse(`"ill-formed gobbledygook'`);
console.log(result.toString()); // Err(SyntaxError: Unterminated string in JSON at position 25)
You could do this once in a utility module and then require that all JSON parsing operations in your code use this version instead.
Transform a function which may throw an error into one with an identical call signature except that it will return a instead of throwing an error.
This allows you to handle the error locally with all the normal
Result
tools rather than having to catch an exception. Where thetryOr
andtryOrElse
functions are useful for a single call, this is useful to make a new version of a function to be used repeatedly.This overload absorbs all exceptions into an
Err
with the typeunknown
. If you want to transform the error immediately rather than using a combinator, see the other overload.Examples
The
JSON.parse
method will throw if the string passed to it is invalid. You can use thissafe
method to transform it into a form which will not throw:You could do this once in a utility module and then require that all JSON parsing operations in your code use this version instead.