Created
January 3, 2012 20:34
-
-
Save geek0x23/1556795 to your computer and use it in GitHub Desktop.
simple express routing PoC for error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Includes | |
var express = require('express'), | |
errors = require('./errors'), | |
NotFound = errors.NotFound, | |
app = module.exports = express.createServer(); | |
// Configuration | |
app.configure(function(){ | |
app.set('views', __dirname + '/views'); | |
app.set('view engine', 'jade'); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(app.router); | |
}); | |
// Error Handling | |
app.use(function(req, res, next) { | |
next(new NotFound(req.url)); | |
}); | |
app.error(function(err, req, res, next) { | |
if (err instanceof NotFound) { | |
console.log('[404]: ', err.name); | |
return res.send('[404]: ' + err.name, { 'Content-Type': 'text/plain' }, 404); | |
} else { | |
console.log('[500]: ', err.stack); | |
return res.send('[500]: ' + err.stack, { 'Content-Type': 'text/plain' }, 500); | |
} | |
}); | |
// Routes | |
require('./routes')(app); | |
// Startup | |
app.listen(3000); | |
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var util = require('util'); | |
function NotFound(path) { | |
this.name = 'Not Found' + (path ? ': ' + path : ''); | |
if (path) { | |
Error.call(this, 'Cannot find ' + path); | |
this.path = path; | |
} else { | |
Error.call(this, 'Not Found'); | |
} | |
Error.captureStackTrace(this, arguments.callee); | |
} | |
util.inherits(NotFound, Error); | |
var exports = module.exports = { | |
NotFound: NotFound | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function(app) { | |
app.get('/bad', function(req, res) { | |
aBadMethodCall(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment