Skip to content

Instantly share code, notes, and snippets.

@WillsB3
Created September 14, 2017 08:23
Show Gist options
  • Save WillsB3/eed90e26f54f3a52cbf9a5d4f564641b to your computer and use it in GitHub Desktop.
Save WillsB3/eed90e26f54f3a52cbf9a5d4f564641b to your computer and use it in GitHub Desktop.
Custom exception creation and usage in JavaScript
// From http://eloquentjavascript.net/08_error.html
// Error definition
function InputError(message) {
this.message = message;
this.stack = (new Error()).stack;
}
InputError.prototype = Object.create(Error.prototype);
InputError.prototype.name = "InputError";
// Code throwing this type of exception
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);
}
// Handling
for (;;) {
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