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

163
Vistas
How do i handle Errors in node express app?

Is there a way to add middleware or app.use() to catch all possible errors?

I have tried some global try-catch approaches but it looks so fragile.

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

0

My approach would be like below

Place below code in

server.js or index.js

   class AppError extends Error {
    constructor(message, statusCode) {
        super(message);

        this.statusCode = statusCode;
        this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
        this.isOperational = true;

        Error.captureStackTrace(this, this.constructor);
    }
}
app.all('*', (req, res, next) => {
    next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});

app.use((err, req, res, next) => {
    err.statusCode = err.statusCode || 500;
    err.status = err.status || 'error';

    res.status(err.statusCode).json({
        status: err.status,
        message: err.message
    });
});
app.use((req, res, next) => {
    console.log("Middleware 1 called.")
    console.log(req.path)
    next() // calling next middleware function or handler
})

app.get('/', (req, res) => {
    console.log("Route handler called.")
    res.send("Hello world!") // response sent back – no more middleware called
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can handle your errors like this:

res.status(500).send({ msg: 'Wrong email' })

And you can change the status code to send different type of errors or responses:

res.status(404).send({ msg: 'Not found' })
res.status(200).send({ msg: 'successful' })
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