Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

errorhandling

View errorhandling.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
// 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?

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;
}

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
Something went wrong with that request. Please try again.