Created
August 18, 2017 15:10
-
-
Save gitfaf/7fe40aab0f6b44f736c92d54fffcf0be to your computer and use it in GitHub Desktop.
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
// http://eloquentjavascript.net/08_error.html | |
var box = { | |
locked: true, | |
unlock: function() { this.locked = false; }, | |
lock: function() { this.locked = true; }, | |
_content: [], | |
get content() { | |
if (this.locked) throw new Error("Locked!"); | |
return this._content; | |
} | |
}; | |
function withBoxUnlocked(body) { | |
var isUnlocked = !box.locked; | |
try { | |
box.unlock(); | |
body(); | |
} catch (e) { | |
console.log(e); | |
} finally { | |
if (!isUnlocked) { | |
box.lock(); | |
} | |
} | |
} | |
withBoxUnlocked(function() { | |
box.content.push("gold piece"); | |
}); | |
try { | |
withBoxUnlocked(function() { | |
throw new Error("Pirates on the horizon! Abort!"); | |
}); | |
} catch (e) { | |
console.log("Error raised:", e); | |
} | |
console.log(box.locked); | |
// → true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment