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

180
Views
How To Deal With Errors In Express Controller / Service Setup?

I have a challenge where I can't really make a decision on how to deal with HTTP responses / Errors in my services and controllers in my Express API. My goal is to have the services be responsible for one thing only and not deal with HTTP at all. Atleast that's my thought.

I would love some feedback on my approach...

I have added general error middlewares:

const errorResponder = (error, req, res, next) => {
  if (error.statusCode && error.message) {
    return res.status(error.statusCode).send(error.message);
  }
  if (error.statusCode) {
    return res.status(error.statusCode).send();
  }
  if (error.message) {
    return res.status(500).send(error.message);
  }
  return next(error); // Forward if above is't triggered
};
const errorFailSafe = (error, req, res, next) => {
  console.log("Fail safe");
  res.status(500).send("Something went wrong, we are digging into it!");
}; 

And then in my controller I unwrap what I need from the req and send to a service. Afterward I send the response back to the client.

findUser: async (req,res,next) => {
    const userId = req.params.userId;
    try {
        // Call service
        const user = await UserService.findOne(userId);
        // Send user back to client
        res.status(200).send(user);
    } catch (error) {
        return next(error)
    }
}

In my service using Sequelize:

findOne: async (userId) => {
  try {
    let user = await db.users.findByPk(userId);
    if (user == null) {
      throw new NotFound("User not found");
    }

    return user;
  } catch (error) {
    throw error;
  }
};

The NotFound error is a custom error class extending Error.

class NotFound extends Error {
  constructor(message) {
    super(message);
    this.statusCode = 404;
  }
}
module.exports =   NotFound ;

Here I kinda break the seperation by having the Service deal with HTTP by calling NotFound. I could change this so it's the Controller doing the check. Would that be better?

Any feedback would be appreciated. :)

about 4 years ago · Santiago Gelvez
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!