A function to wrap so it never throws an error or produces a
Promise
rejection.
Given a function which returns a Promise
and a function to transform thrown
errors or Promise
rejections resulting from calling that function, return a
new function with the same parameters but which returns a Task
.
To catch all errors but leave them unhandled and unknown
, see the other
overload.
You can use this to create a safe version of the fetch
function, which will
produce a Task
instead of a Promise
and which does not throw an error for
rejections, but instead produces a {@Rejected } variant of the Task
.
import { safe } from 'true-myth/task';
class CustomError extends Error {
constructor(name: string, cause: unknown) {
super(`my-lib.error.${name}`, { cause });
this.name = name;
}
}
function handleErr(name: string): (cause: unknown) => CustomError {
return (cause) => new CustomError(name);
}
const fetch = safe(window.fetch, handleErr('fetch'));
const toJson = safe(
(response: Response) => response.toJson(),
handleErr('json-parsing')
);
let json = fetch('https://www.example.com/api/users').andThen(toJson);
Given a function which returns a
Promise
, return a new function with the same parameters but which returns aTask
instead.If you wish to transform the error directly, rather than with a combinator, see the other overload, which accepts an error handler.
Examples
You can use this to create a safe version of the
fetch
function, which will produce aTask
instead of aPromise
and which does not throw an error for rejections, but instead produces a {@Rejected } variant of theTask
.