Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
Error thrown by a class method is not catched by a request handler

I created a transporter class to send emails:

export class MailTransporter {
  receiver: string;
  private transporter: Transporter;

  constructor(receiver: string) {
    this.receiver = receiver;
    this.transporter = this.getTransporter();
  }

  private getTransporter() {
    const { MAIL_USERNAME: user, MAIL_PASSWORD: pass, MAIL_HOST: host, MAIL_PORT: port } = process.env;

    if (!user || !pass || !host || port) {
      // NEXT LINE THROWS AN ERROR
      throw new Error('Specify MAIL_USERNAME, MAIL_PASSWORD, MAIL_HOST and MAIL_PORT in .env');
    }

    const transporter = nodemailer.createTransport({
      host,
      port: Number(port),
      secure: true,
      auth: {
        user,
        pass,
      },
    });

    return transporter;
  }

  public async sendMail(formValues: string) {
    const values: FormValues = JSON.parse(formValues);
    const message: SendMailOptions = {...};

    await this.transporter.sendMail(message, (err, info) => {
      if (err) {
        throw err;
      }

      console.log('Email successfully sent. Info:\n', info);
    });
  }
}

And calling sendMail function from within handler function:

export default async function Handler(req: NextApiRequest, res: NextApiResponse) {
  const { body } = req;

  try {
    const response = await MessageTransporter.sendMail(body); //MessageTransporter is an instance of MailTransporter

    res.status(200).json({ success: true, message: 'OK' });
  } catch (error) {
    res.json({ success: false, message: 'Could not send the message' });
  }
}

But the error thrown in MailTransporter isn't being catched in Handler, instead I'm getting the error in my console image
And in my browser I'm getting 500 error on my POST request.

Could you please explain what's going on there? Why the error isn't catched inside try catch of handler?

Also, I'm kinda new to js classes so if you have anything to say about class design, please do.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The call to getTransporter is inside the constructor of MailTransporter, so you should be checking it at the invocation site where the instance of MessageTransporter is getting created.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda