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

245
Visualizações
Node js with typescript; How to catch express errors

So if I am using node js with javascript, I used to catch errors by adding the following code in my app.js startup file:

app.use((req, res, next) => {   next(createError.NotFound()); });

app.use((err, req, res, next) => {
  res.status(err.status || 500).json({
    status: err.status || 500,
    success: 0,
    message: 'Error',
    error: [err.message],
    data: {}
  });
});

the "err" will be automatically caught and it will return for example 404 if I am using a route that does not exist or 500 if the database connection is not established correctly and so on.

But in typescript, how can I do the same logic?

My app.ts file is as follows

import express, { Application, Request, Response, NextFunction } from 'express';
    import routes from './start/routes';
    
    const app: Application = express();
    app.use('/', require('./routes/api.route'));
    
    app.use(express.json());
    app.use('/api', routes);
    
app.use((err, req: Request, res: Response, next: NextFunction ) => {
    res.status(err.status || 500).json({
        status: err.status || 500,
        success: 0,
        message: 'Error',
        error: [err.message],
        data: {}
    });
});
    
    const PORT = process.env.PORT || 3001;
    app.listen(PORT, () => console.log(`🚀 @ http://localhost:${PORT}`));

this is not compiling. It says that err.status and err.message are not found. What to do?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are missing the type for the err parameter, which should be any according to the ErrorRequestHandler type. ErrorRequestHandler Type

This will make your code compile, and the handler will run automatically when an error occurs.

To make a default response to 404 though. You will need to add another handler since it's not an error.

 app.use((req: Request, res: Response, next: NextFunction ) => { 
    // Handle not found
})

NOTE This handler should be last since it accepts every request.

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