Created
October 10, 2012 13:12
-
-
Save ProjectMoon/3865578 to your computer and use it in GitHub Desktop.
errorhandling
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
//A third way. | |
//In a business logic module. Note: replace "internal" methods with your own logic (redis, mongodb, etc). | |
function getBlogByGuid(id, callback) { | |
internalLoad(id, function(err, post) { | |
if (err) return callback(err); | |
}); | |
} | |
function deleteDocumentById(id, callback) { | |
internalDelete(id, function(err) { | |
callback(err); //err will either be an error, or null/undefined. | |
}); | |
} | |
function handleDelete(id, callback) { | |
getBlogByGuid(id, function(err, post) { | |
if (err) return callback(err); | |
deleteDocumentById(id, function(err) { | |
callback(err); //again, err will be an error or null/undefined. | |
}); | |
}); | |
} | |
//Somewhere in your web code... | |
var business = require('./business'); //has the business logic | |
app.post('/my/delete/url/', function(req, res) { | |
if (!('guid' in request.url.query)) { | |
handleError(new Error('Missing guid')); | |
} | |
business.handleDelete(request.query.guid, function(err) { | |
if (err) return handleError(err, res); | |
res.send(200, 'Blog deleted'); | |
}); | |
}); | |
//Error handler will handle Error objects or strings--though it's recommended to pass in Errors only. | |
function handleError(error, res) { | |
if (errorinstanceof Error) { | |
res.send(500, error.message); | |
} | |
else if (typeof error== 'string' || error instanceof String) { | |
res.send(500, error); | |
} | |
else { | |
throw new Error('Unrecognized type for error handler.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment