Skip to content

Instantly share code, notes, and snippets.

@calvinxiao
Created August 29, 2015 16:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calvinxiao/ada4a6f4314acd984246 to your computer and use it in GitHub Desktop.
Save calvinxiao/ada4a6f4314acd984246 to your computer and use it in GitHub Desktop.
Better error handling example with NodeJs & restify
// 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