Created
August 29, 2015 16:34
-
-
Save calvinxiao/ada4a6f4314acd984246 to your computer and use it in GitHub Desktop.
Better error handling example with NodeJs & restify
This file contains 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
// Demostrate how to handle error in nodejs server | |
var restify = require('restify'); | |
function getHello(req, res, next) { | |
throw new Error('standard error happens here'); | |
} | |
function postHello(req, res, next) { | |
throw new MyError('here is my error'); | |
} | |
var server = restify.createServer(); | |
server.get('/hello/:name', getHello); | |
server.post('/posthello/:name', postHello); | |
server.listen(8080, function() { | |
console.log('%s listening at %s', server.name, server.url); | |
}); | |
// custom your own error | |
function MyError(message) { | |
this.message = message; | |
Error.captureStackTrace(this, MyError); | |
} | |
MyError.prototype = Object.create(Error.prototype); | |
MyError.prototype.constructor = MyError; | |
// end MyError | |
server.on('MethodNotAllowed', function (req, res, err) { | |
console.log(err.stack); | |
res.send(400, 'screw you!'); | |
//additional logging | |
console.log('not allowed?'); | |
}); | |
server.on('uncaughtException', function (req, res, route, err) { | |
console.log(route); // log the route, woo... | |
console.log(err.stack); // log the stack | |
var message = 'WTF'; | |
if (err instanceof MyError) { | |
message = err.message; | |
} | |
res.send(400, { message: message }); // status code can depend on the Error Type | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment