dword-design / nuxt-mail

Adds email sending capability to a Nuxt.js app. Adds a server route, an injected variable, and uses nodemailer to send emails.
Other
239 stars 18 forks source link

useFetch does not seem to throw an error to catch #142

Closed silverbackdan closed 1 year ago

silverbackdan commented 1 year ago

Sorry for another issue, but it looks to me as though useFetch simply returns a FetchError in a vue ref variable error so to return an error it shouldn't be trying to catch it.

Something like this should work I believe

import { useFetch } from "#app";
import SMTPTransport from "nodemailer/lib/smtp-transport";

export default defineNuxtPlugin(() => {
  const send = async (config: SMTPTransport) => {
    const { error } = await useFetch("/mail/send", {
      body: config,
      method: "POST",
    });
    if (error.value) {
      throw new Error(error.value?.data);
    }
  };
  return {
    provide: {
      mail: {
        send
      },
    },
  };
});
atinux commented 1 year ago

I don't recommend to use useFetch for sending POST action but instead using $fetch directly.

silverbackdan commented 1 year ago

Cool, in that case it's probably prudent to update https://github.com/dword-design/nuxt-mail/blob/master/src/plugin-nuxt3.js

Something like this which could be typescript instead of js as well.

import SMTPTransport from "nodemailer/lib/smtp-transport";
import {$fetch, FetchError} from 'ofetch';

export default defineNuxtPlugin(() => {
  const send = async (config: SMTPTransport) => {
    try {
      await $fetch("/mail/send", {
        body: config,
        method: "POST",
      });
    } catch (error) {
      if (error instanceof FetchError) {
        throw new Error(error.response?._data)
      }
      throw error
    }
  };
  return {
    provide: {
      appMail: {
        send
      },
    },
  };
});
silverbackdan commented 1 year ago

Thanks @dword-design