Skip to content

How can I catch client error event? #5894

Answered by AtilMohAmine
GwangIl-Park asked this question in Q&A
Discussion options

You must be logged in to vote

Here's an example of how you can configure timeout handling for your routes in Express:

// Middleware to handle timeouts
app.use((req, res, next) => {
  req.setTimeout(5000, () => {
    const error = new Error('Request Timeout');
    error.status = 408; // Request Timeout
    next(error);
  });
  next();
});

// Your test route
app.post('/test', async (req: Request, res: Response) => {
  // Simulating delay
  await sleep(6000);
  res.status(200).send();
});

// Error handling middleware
app.use((err, req, res, next) => {
  if (res.headersSent) {
    return next(err);
  }

  logger.error('Request Error:', err);
  res.status(err.status || 500).json({ error: err.message });
});

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by IamLizu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #5317 on September 02, 2024 16:45.