Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda