Created
March 20, 2014 22:42
-
-
Save jeduan/9675592 to your computer and use it in GitHub Desktop.
Error handling in express 4
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 express = require('express'), | |
logger = require('morgan') | |
var app = express(); | |
var env = process.env.NODE_ENV || 'development'; | |
var silent = env === 'test' | |
app.set('port', +process.env.PORT || 3000) | |
if (env === 'development') { | |
app.use(logger('dev')) | |
} else { | |
app.use(logger()) | |
} | |
app.use(require('body-parser')()) | |
app.use(require('method-override')()) | |
app.route('/').get(function (req, res) { | |
res.json({hello: 'world'}) | |
}) | |
app.use(function handleNotFound(req, res, next){ | |
res.status(404); | |
if (req.accepts('html')) { | |
res.render('404', { url: req.url }); | |
return; | |
} | |
if (req.accepts('json')) { | |
res.send({ error: 'Not found' }); | |
return; | |
} | |
res.type('txt').send('Not found'); | |
}) | |
if (env === 'development') { | |
app.use(require('errorhandler')()) | |
} else { | |
app.use(function logErrors(err, req, res, next){ | |
if (err.status === 404) { | |
return next(err) | |
} | |
console.error(err.stack) | |
next(err) | |
}) | |
app.use(function respondError(err, req, res, next){ | |
var status, message | |
status = err.status || 500 | |
res.status(status) | |
message = ((err.productionMessage && err.message) || | |
err.customProductionMessage) | |
if (!message) { | |
if (status === 403) { | |
message = 'Not allowed' | |
} else { | |
message = 'Oops, there was a problem!' | |
} | |
} | |
if (req.accepts('json')) { | |
res.send({error: message}) | |
return | |
} else { | |
res.type('txt').send(message + '\n') | |
return | |
} | |
}) | |
} | |
if (!module.parent) { | |
app.listen(app.get('port')) | |
if (!silent) { | |
console.log('Server listening on port ' + app.get('port')) | |
} | |
} |
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
{ | |
"name": "errors-test", | |
"version": "0.0.0", | |
"description": "", | |
"main": "index.js", | |
"author": "Jeduan Cornejo <[email protected]> (http://jeduan.com/)", | |
"license": "ISC", | |
"dependencies": { | |
"express": "~4", | |
"morgan": "~1.0.0", | |
"body-parser": "~1.0.0", | |
"errorhandler": "~1.0.0", | |
"method-override": "~1.0.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment