Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// app.js
// ...
app.use(app.router);
app.use(express['static'](path.join(__dirname, 'public'), {
maxAge: 31557600000
}));
// set global locals
app.locals({
pkg: pkg,
bust: Date.now()
});
// www redirect
app.use(function(req, res, next) {
if (req.headers.host.match(/^www/) !== null) {
res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url, 301);
} else {
next();
}
});
// app router
require('./routes/index')(app);
// handle errors
require('./lib/errors')(app);
// ...
// lib/errors.js
module.exports = function(app) {
app.use(function(req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('404', {
url: req.url
});
return;
}
// respond with json
if (req.accepts('json')) {
res.send({
error: 'Not found'
});
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
app.use(function(err, req, res, next) {
err = err.stack || err;
// email error to admin
app.get('email').sendMail({
subject: 'Fatal Exception',
text: err
}, function(error, response) {
if (error) {
console.log(error);
} else {
console.log("Error message sent: " + response.message);
}
});
// output to stderr
console.error(err);
res.status(500);
// respond with html page
if (req.accepts('html')) {
res.render('500', {
status: 500,
statusText: err
});
return;
}
// respond with json
if (req.accepts('json')) {
res.send({
error: err
});
return;
}
// default to plain-text. send()
res.type('txt').send(err);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.