Last active
July 19, 2021 23:48
-
-
Save mtHuberty/d990b0fb6f9416606be3d36b49898200 to your computer and use it in GitHub Desktop.
A nice lil' JS error handling pattern
This file contains hidden or 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
function thisThrows() { | |
throw new Error('Original error') | |
} | |
function thisAddsContextAndThrowsAgain() { | |
try { | |
thisThrows() | |
} catch(err) { | |
err.message = 'More info: ' + err.message | |
err.statusCode = 404 | |
throw err // note that we don't `throw new Error(err)` or we lose some stack info | |
} | |
} | |
function main() { | |
try { | |
thisAddsContextAndThrowsAgain() | |
} catch(err) { | |
console.log(err.statusCode) // prints 404 | |
console.error(err) // prints the message with stack below | |
/* | |
customError.js:20 Error: More info: Original error | |
at thisThrows (VM200 customError.js:2) | |
at thisAddsContextAndThrowsAgain (VM200 customError.js:7) | |
at main (VM200 customError.js:17) | |
at VM200 customError.js:24 | |
*/ | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a little pattern I like for modifying errors in JS. Modifying the err.message will add info anywhere it's toString()'d (like console.log), and re-throwing the error will add stack trace info at each
throw
location. Also, you can add your own custom keys to the err object. Though even with typescript, there's no good way to gain type safety on thrown errors, so do this carefully.