Skip to content

Instantly share code, notes, and snippets.

@AWaselnuk
Created December 16, 2014 21:49
Show Gist options
  • Save AWaselnuk/601013b6bcc3488772f8 to your computer and use it in GitHub Desktop.
Save AWaselnuk/601013b6bcc3488772f8 to your computer and use it in GitHub Desktop.
Selective error catching in JavaScript
// 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