Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!