timolins / react-hot-toast

Smoking Hot React Notifications 🔥
https://react-hot-toast.com
MIT License
9.66k stars 319 forks source link

Allow to pass a plain error #236

Open franciscop opened 1 year ago

franciscop commented 1 year ago

Feature request: allow to pass a plain Error instance to toastr.error() (and maybe to toastr() itself) that will properly display it as an error. IMHO this code looks intuitive enough but it wouldn't work right now:

toastr(new Error("my error"));   // Does not work
toastr.error(new Error("my error"));   // Also does not work

Edit: a big advantage of this is that you'd be able to simplify promise handling like:

mypromise.then(...).catch(toastr);  // First case
mypromise.then(...).catch(toastr.error);  // Second case

Could be as easy as a well situated:

// Before
const toast = (message: Message, opts?: ToastOptions) =>
  createHandler('blank')(message, opts);

// After
const toast = (message: Message, opts?: ToastOptions) => {
  if (message instanceof Error) {
    return createHandler('error')(message.message, opts);
  }
  return createHandler('blank')(message, opts);
};

Or handling it lower in the chain, so that any toastr.[whatever](new Error(...)) becomes an .error(...) type:

// Before
const createHandler =
  (type?: ToastType): ToastHandler =>
  (message, options) => {
    const toast = createToast(message, type, options);
    dispatch({ type: ActionType.UPSERT_TOAST, toast });
    return toast.id;
  };

// After
const createHandler =
  (type?: ToastType): ToastHandler =>
  (message, options) => {
    if (message instanceof Error) {
      type = 'error';
      mesage = message.message;
    }
    const toast = createToast(message, type, options);
    dispatch({ type: ActionType.UPSERT_TOAST, toast });
    return toast.id;
  };