SafeFn
Creating a SafeFn

Handling uncaught errors

As this library is built around NeverThrow, ideally you should handle errors in your function and return them as values. However, some functions could throw unexpectedly. To handle this you can provide you can provide an uncaught error handler via catch(), which receives the uncaught error as an argument and should return an Err value.

const mySafeFn = createSafeFn()
  .handler(() => {
    if (Math.random() > 0.5) {
      throw new Error();
    }
    return ok("Success");
  })
  .catch((e) => {
    //    ^? (parameter) e: unknown (not typed as Error as anything can be thrown in JS)
    return err("Ooh no!");
  });
 
const res = await mySafeFn.run();
//   ^? Result<"Success", "Ooh no!">

I'd recommended to always shape your errors as an object with a code key, to make it easy to narrow the type of them down when handling them.

If you don't provide an uncaught error handler, the default error handler will be used:

(error: unknown) => {
  console.error(error);
  return err({
    code: "UNCAUGHT_ERROR",
    cause:
      "An uncaught error occurred. You can implement a custom error handler by using `catch()`",
  } as const);
};

Next.js relies on throwing errors for redirect() and notFound(). These errors are filtered out and will still be thrown and thus not hit your catch handler.

On this page

No Headings