Created
December 16, 2014 21:49
-
-
Save AWaselnuk/601013b6bcc3488772f8 to your computer and use it in GitHub Desktop.
Selective error catching in JavaScript
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
// from: Eloquent JavaScript http://eloquentjavascript.net/08_error.html#p_CJKevweHV6 | |
// Define our own error type | |
function InputError(message) { | |
this.message = message; | |
this.stack = (new Error()).stack; | |
} | |
InputError.prototype = Object.create(Error.prototype); | |
InputError.prototype.name = "InputError"; | |
// Check for instances of that error type and rethrow if needed | |
function promptDirection(question) { | |
var result = prompt(question, ""); | |
if (result.toLowerCase() == "left") return "L"; | |
if (result.toLowerCase() == "right") return "R"; | |
throw new InputError("Invalid direction: " + result); | |
} | |
for (;;) { // Loops until explicitly broken | |
try { | |
var dir = promptDirection("Where?"); | |
console.log("You chose ", dir); | |
break; | |
} catch (e) { | |
if (e instanceof InputError) | |
console.log("Not a valid direction. Try again."); | |
else | |
throw e; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment