express
express copied to clipboard
How can I catch client error event?
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
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 });
});