How to customise time-out response using Express and connect-timeout?

1.9k views Asked by At

I want to customise the response sent to the users when a timeout error is fired. More specifically, I want to redirect them to a static page explaining why a timeout error has been fired.

I want to write something like :

var express = require('express')
var timeout = require('connect-timeout')
var app = express();

var port = process.env.PORT || 8080;

app.use(timeout(10,{"respond":true}));
app.use(haltOnTimedout);

// GET ROUTES HERE

app.listen(port, function() {
    console.log('Our app is running on port '+ port);
});

function haltOnTimedout(req,res,next) {
    if (req.timedout) {
        res.redirect('/timedout.html');
    } else {
        next();
    }
};

The code above is not working as intended : even if a timeout is fired, it does not redirect the user to the static webpage timedout.html, instead it throws the error ServiceUnavailableError: Response timeout

Is it possible to do something like this or am I missing something ?

1

There are 1 answers

0
ldc On

I finally find the answer and post it here if someone get the same question.

I placed the following line of code at the very end of my server.js code :

app.use(haltOnTimedout);
function haltOnTimedout(err,req,res,next) {
    if (req.timedout === true) {
        if (res.headersSent) {
            next(err);
        } else {
            res.redirect('/timedout.html');
        }
    } else {
        next();
    }
};

and add if (!req.timedout) { res.send(something);} in all routes in order to avoid double send of the headers.