Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!