Create a gist now

Instantly share code, notes, and snippets.

errorhandling
// Lovely simple-to-read code:
function handleDelete(request, response) {
getBlogByGuid(request.url.query.guid, function gotBlog(err, blog) {
deleteDocumentById(blog.id, function deletedBlog(err, status) {
// Deleted OK
response.writeHead(200);
response.end('Blog Deleted');
})
});
}
// Now with some error checking:
function handleDelete(request, response) {
if ( ! "guid" in request.url.query)) {
console.log('Blogs', 'Error - Missing guid in handleDelete');
response.setHeader('Content-Type','application/json');
response.writeHead(400);
response.end(JSON.stringify("Missing guid"));
return;
}
getBlogByGuid(request.url.query.guid, function gotBlog(err, blog) {
if(err == true) {
console.log('Blogs', 'Error in getBlogByGuid callback in handleDelete');
response.setHeader('Content-Type','application/json');
response.writeHead(500);
response.end(JSON.stringify(err));
return;
}
deleteDocumentById(blog.id, function deletedBlog(err, status) {
if(err == true) {
console.log('Blogs', 'Error in deleteDocumentById callback in handleDelete');
response.setHeader('Content-Type','application/json');
response.writeHead(500);
response.end(JSON.stringify(err));
return;
}
// Deleted OK
response.writeHead(200);
response.end('Blog Deleted');
})
});
}
// :( What happened to my lovely readable code?
@BrianTheCoder

you can extract all the error reporting code into a separate function

function reportError(msg, err) {
    console.log('Blogs', msg);
        response.setHeader('Content-Type','application/json');
        response.writeHead(500);
        response.end(JSON.stringify(err));
        return;
}
@BrianTheCoder

Here's my fork https://gist.github.com/3867138. Still not as pretty as the first one, but much better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment