Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Created February 10, 2012 16:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save briancavalier/1790826 to your computer and use it in GitHub Desktop.
Save briancavalier/1790826 to your computer and use it in GitHub Desktop.
Messy async handling of error conditions
function thisMightFail(callback, errback) {
xhrGet('/result', callback, errback);
}
function recoverFromFailure(callback, errback) {
recoverAsync(
function(result) {
if(callback) {
try {
callback(result);
} catch(e) {
// Ok, callback threw an exception, let's switch to errback
// At least this will let the caller know that something went wrong.
// But now, both the callback and errback will have been called, and
// and the developer may not have accounted for that!
errback(e);
}
}
}
function(error) {
if(errback) {
try {
errback(error);
} catch(ohnoes) {
// What do we do now?!?
// We could re-throw or not catch at all, but no one can catch
// the exception because this is all asynchronous.
// And now console.error has infiltrated deep into our code, too!
console.error(ohnoes);
}
}
},
);
}
function getTheResult(callback, errback) {
// Simulating the catch-and-recover behavior of try/catch
thisMightFail(callback, function(e) {
recoverFromFailure(callback, errback);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment