Things no one told you about error handling in JS

Why your error handling is not working?

try{anAsyncFunction().then(//do something which can throw an error)}catch(e){}
//in this case error will not be caught because of the reason stated above
Codepen link:

Open inspect mode at Codepen, console will have an uncaught error


window.addEventListener('unhandledrejection', function(event) {})


Use callbacks instead of async function


Use async error handling



Use multiple catch

let anAsyncFunction = async()=>{ return null}try{


throw 'shit happens'
document.body.innerHTML = e


document.innerHTML = e
Codepen link:

This time there will be no uncaught error

You don’t need to throw error object

try{throw Error('shit happens')
console.log(e.message) // it will console log "shit happens"

throw Error creates an error object that contains the line where this error originated, and the message but if you only desire to use error message you can instead throw only message.

yes! that is possible.

try{throw 'shit happens'
console.log(e) // it will console log "shit happens"
}similarly you can throw objects constants arrays any JS object

but you won’t be able to know the line error originated from

Finding Magic.