From 47378fb978785a3e5470aec372908d66994e3e69 Mon Sep 17 00:00:00 2001 From: Baris Usakli Date: Mon, 8 Jul 2013 16:02:54 -0400 Subject: [PATCH] error middleware, closes #60 --- src/routes/user.js | 8 +++++--- src/webserver.js | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/routes/user.js b/src/routes/user.js index 7aa8990032..273ab0e74f 100644 --- a/src/routes/user.js +++ b/src/routes/user.js @@ -43,15 +43,16 @@ var user = require('./../user.js'), res.send(app.build_header(res) + app.create_route("users-search", "users") + templates['footer']); }); - app.get('/users/:userslug', function(req, res) { + app.get('/users/:userslug', function(req, res, next) { + if(!req.params.userslug) { - res.send("User doesn't exist!"); + next(); return; } user.get_uid_by_userslug(req.params.userslug, function(uid) { if(!uid) { - res.redirect('/404'); + next(); return; } @@ -60,6 +61,7 @@ var user = require('./../user.js'), }); app.get('/users/:userslug/edit', function(req, res) { + console.log('derp'); if(!req.user) return res.redirect('/403'); diff --git a/src/webserver.js b/src/webserver.js index e6a346944a..f92646fce5 100644 --- a/src/webserver.js +++ b/src/webserver.js @@ -58,6 +58,8 @@ var express = require('express'), } auth.initialize(app); + + app.use(app.router); app.use(function(req, res, next) { // Don't bother with session handling for API requests @@ -72,7 +74,40 @@ var express = require('express'), next(); }); - + + app.use(function(req, res, next) { + res.status(404); + + // respond with html page + if (req.accepts('html')) { + + //res.json('404', { url: req.url }); + res.redirect('/404'); + return; + } + + // respond with json + if (req.accepts('json')) { + console.log('sending 404 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) { + // we may use properties of the error object + // here and next(err) appropriately, or if + // we possibly recovered from the error, simply next(). + console.error(err.stack); + + res.status(err.status || 500); + + res.json('500', { error: err.message }); + }); + auth.create_routes(app); admin.create_routes(app); userRoute.create_routes(app);