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

159
Views
Express middleware not catching errors

With using express and typescript I'm trying to create an middleware to catch errors like eq. Sentry, code is below:

 const catchError = (
  error: Error,
  req: Request,
  _res: Response,
  next: any
) => {
   console.log("ERROR: ", error);
   //some logic

  next(error);
}

index.ts

  app.use(bodyParser.json({ limit }));
  app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));

  app.use(express.json());
  app.use(cors({ credentials: true, origin: true }));

  app.use(bodyParser.urlencoded({ extended: false }));
//controllers

app.use(catchError as express.ErrorRequestHandler)

why my middleware is working only when i put:

} catch (error) { 
   next(error);
}

in function where is an error and not working without it? This middleware should also catching errors and exceptions without using next(error)

thanks for any help!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think you need to add a method override to use that custom error handler.


const methodOverride = require('method-override')

app.use(bodyParser.json({ limit }));
app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));

app.use(express.json());
app.use(cors({ credentials: true, origin: true }));

app.use(bodyParser.urlencoded({ extended: false }));

// Try to use this to override the custom error handler
app.use(methodOverride())

app.use(catchError as express.ErrorRequestHandler)

Reference:

https://expressjs.com/en/guide/error-handling.html

https://www.npmjs.com/package/method-override

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!