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

212
Vistas
How can I pass errors from Services to Controllers in Node.js?

I am trying to work in authentification in an organized way having a controller and service as follows. Although it has been a struggle to find a way to pass the error messages from services to controllers. The user is saved, but if I want to check it the email already exists nothing happens.

Controller:

const { isEmail, isEmpty } = require("../middleware/authMiddlewareValidators");
const { newUser } = require("../services/authServices");

// Register
exports.register = async (req, res) => {
  const { firstName, lastName, email, password } = req.body;

  if (isEmpty(email)) {
    res.status(400).json({ message: "Email must not be empty" });
    return;
  }
  if (!isEmail(email)) {
    res.status(400).json({ message: "Please provide a valid email adress" });
    return;
  }

  if (isEmpty(password)) {
    res.status(400).json({ message: "Password must not be empty" });
    return;
  }
  if (password.length < 6) {
    res
      .status(400)
      .json({ message: "Password must have at least 6 characters" });
    return;
  }

  try {
    await newUser(firstName, lastName, email, password)
    res.status(200).json({ message: "signup success! please login." });
  } catch (error) {
    console.log(error);
    res.status(500).json({message: error})
  }
};

Service:

const User = require("../models/User-model");
const bcrypt = require("bcryptjs");
const passport = require("passport");
const { transporter } = require("../configs/nodemailer");

exports.newUser = async (firstName, lastName, email, password) => {
  try {
    let user = await User.findOne({ email });
    
    if (user) {
      throw new Error("This email is already taken");
    } else {
      const salt = bcrypt.genSaltSync(10);
      const hashPass = bcrypt.hashSync(password, salt);

      const newUser = new User({
        firstName: firstName,
        lastName: lastName,
        email: email,
        password: hashPass,
      });

      newUser.save(() => {
        transporter.sendMail({
          to: newUser.email,
          from: process.env.SCHOOLSCOOL_EMAIL,
          subject: "Succefull register!",
          html: `<p>Welcome to School's Cool ${newUser.firstName} ${newUser.lastName}, <br>
                  <br> Please login to use the web application. <br><br> Thank you.</p>`,
        });
      });
    }
  } catch (error) {
    throw new Error(error.message);
  }
};

Not sure what am I doing wrong but I can't pass the message if the user already exists...

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

0

you can make the service returns an object:

return {
  type: 'Error',
  message: err
};

and if there is no errors it will return the same object with type and message and if there are some data you will put it in the same object like this:

return {
   type: 'Success',
   statusCode: 200,
   message: 'Users found successfully',
   users
};

then you will recieve these data in your controller using object destructing:

const {type, message, statusCode, users} = await userServices.getUsers();

and finally you can check whether the type is Error or Success

if (type === 'Error){
  return res.status(statusCode).json({type, message});
}
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