Things no one told you about error handling in JS

Why your error handling is not working?

Error won’t be caught if error is thrown inside a ‘then’ method of an async function, The try catch block executes before the async function is executed (yes! error handling in JS is synchronous), but the error is thrown at a latter point in time when that async function is executed

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: https://codepen.io/arnavsingh/pen/MWKLRjP?editors=0010

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

Solutions

Use unhandled rejection event

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

or

Use callbacks instead of async function

or

Use async error handling

anAsyncFunction.then(errorProneFunction).catch(error=>{})

or

Use multiple catch

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

anAsyncFunction().then(()=>{

try{
throw 'shit happens'
}catch(e){
document.body.innerHTML = e
}

})

}catch(e){
document.innerHTML = e
}
Codepen link: https://codepen.io/arnavsingh/pen/MWKLRjP?editors=0010

This time there will be no uncaught error

You don’t need to throw error object

Generally we desire to extract error message in catch block by this

try{throw Error('shit happens')
}catch(e){
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'
}catch(e){
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.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

6 Things You Need To Completely Understand Array Destructuring in Javascript (ES6)

Creating Pie Chart Using Canvas

5 Useful Tricks JavaScript has been Hiding from You

Client Side VS Server Side Rendering

Week 8, and end to one journey…

Best CSS frameworks to Check Out in 2021

Leetcode Q241. Different Ways to Add Parentheses (Q233)

Redux one liner…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arnav Zedian

Arnav Zedian

Finding Magic.

More from Medium

MVC (Model View Controller)

Introduction to Application Development: Client Layer

Software engineering principles, best practices & introduction to JavaScript.

Learned Java script for free!!!

Scrimba.com Screen shot