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

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

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 Report

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