Skip to content

Instantly share code, notes, and snippets.

@youtalk
Created January 12, 2012 06:37
Show Gist options
  • Save youtalk/1599082 to your computer and use it in GitHub Desktop.
Save youtalk/1599082 to your computer and use it in GitHub Desktop.
Error handling for Node.js
var NotFoundError = module.exports.NotFoundError = function (message) {
this.name = 'NotFoundError: ' + message;
Error.call(this, message);
Error.captureStackTrace(this, arguments.callee);
};
NotFoundError.prototype.__proto__ = Error.prototype;
var UnauthorizedError = module.exports.UnauthorizedError = function (message) {
this.name = 'UnauthorizedError: ' + message;
Error.call(this, message);
Error.captureStackTrace(this, arguments.callee);
};
UnauthorizedError.prototype.__proto__ = Error.prototype;
var BadRequestError = module.exports.BadRequestError = function (message) {
this.name = 'BadRequestError: ' + message;
Error.call(this, message);
Error.captureStackTrace(this, arguments.callee);
};
BadRequestError.prototype.__proto__ = Error.prototype;
app.error(function (err, req, res, next) {
console.log(err.message || 'Error: ocur unknown error');
console.log(err.stack);
var error = new mongodb.errors(
{ stack: middle.sanitize(err.stack), message: middle.sanitize(err.message) });
error.save(middle.log());
if (err instanceof BadRequestError) {
res.local('title', 'Bad Request');
res.local('status', 400);
} else if (err instanceof UnauthorizedError) {
res.local('title', 'Unauthorized');
res.local('status', 401);
} else {
res.local('title', 'Not found');
res.local('status', 404);
}
res.render('error', {
url: req.url,
error: error });
});
app.use(function (req, res, next) {
var message = 'NotFoundError: cannot find ' + req.url;
console.log(message);
var error = new mongodb.errors(
{ message: middle.sanitize(message) });
error.save(middle.log());
res.render('error', {
title: 'Not found',
status: 404,
url: req.url,
error: false
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment