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

186
Vistas
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
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