Skip to content

Instantly share code, notes, and snippets.

@kephin
Last active September 2, 2018 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kephin/abdf4c0dd1bd1dce154643551298eb55 to your computer and use it in GitHub Desktop.
Save kephin/abdf4c0dd1bd1dce154643551298eb55 to your computer and use it in GitHub Desktop.
// Start a method chain that will throw an error:
// --> foo() [catches error]
// -----> bar() [catches / rethrows error]
// --------> baz() [throws error]
foo();
function foo() {
try {
bar();
} catch ( error ) {
console.log( `Error caught in Foo(): ${error.message}` );
console.log( error.stack );
}
}
function bar() {
// In this case, we are going to catch any errors thrown by baz(), log them to the
// console, and then rethrow them.
try {
baz();
} catch ( error ) {
console.log( `Error caught and rethrown in Bar(): ${error.message}` );
// In JavaScript, there is no special "rethrow" keyword. You simply throw() the
// error that you caught. This will maintain the original stacktrace recorded by
// the error as you "pass it back up" the call-stack.
throw( error );
}
}
function baz() {
const error = new Error();
error.name = 'customError';
error.message = 'hello world';
throw(error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment