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

243
Vistas
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 Respuestas
Responde la pregunta

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