Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I catch client error event? #5317

Open
GwangIl-Park opened this issue Nov 13, 2023 · 1 comment
Open

How can I catch client error event? #5317

GwangIl-Park opened this issue Nov 13, 2023 · 1 comment

Comments

@GwangIl-Park
Copy link

GwangIl-Park commented Nov 13, 2023

Can I catch client error event like POST, PUT, etc?

I should catch client error like timeout, disconnect.

So I tried like below in log middleware.

req.on("error", (error:Error) => {
      logger.error("Request Error : ", error);  
    });

With GET method, it worked

Error: aborted
at connResetException (node:internal/errors:704:14)
at abortIncoming (node:_http_server:625:17)
at socketOnClose (node:_http_server:619:3)
at Socket.emit (node:events:525:35)
at TCP.<anonymous> (node:net:757:14)

But with other method, it did not work..

This is my testcode in server. For test with timeout, I use sleep.

this.router.post(`/test`, async(req:Request,res:Response)=>{
      await sleep(100)
      res.status(200).send()
    });

I'm using express 4.18 and node version 18

@AtilMohAmine
Copy link

AtilMohAmine commented Nov 24, 2023

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 });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants