Last active
September 2, 2018 07:24
-
-
Save kephin/abdf4c0dd1bd1dce154643551298eb55 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
// 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