JavaScript has a built in error object that provides error information when an error occurs. The error object provides two useful properties: name and message.
“Exceptions are for exceptional things. It’s for when that something we were hoping didn’t happen, yeah, that just happened.” -Curry
Note: don’t be too detailed in the error
Prefer control flow over error handling where you can. This includes if statements, switches, loops, etc. Alternatively you can throw an error. Using error handling as if it’s control flow isn’t recommended. Error handling should be for exceptions, things you are not sure how to handle.
.catch()
try {
} catch(err) {
} finally {
}
from the fireship video:
await step1().catch(fun)
but this can still get repetitive so:
async function awesome() {
try {
const data = await promise
return [data, null]
} catch(err) {
console.error(err)
return [null, error]
}
}
now you can call to get a clean one liner
async function main() {
const [data, error] = await awesome()
const [data2, error2] = await awesome()
const [data3, error3] = await awesome()
}
Or use an “if statement” if you want to do something else with the error
async function main() {
const [data, error] = await awesome()
if (error) {}
const [data2, error2] = await awesome()
const [data3, error3] = await awesome()
}
throw {error: "whatEvs", code: 239}
Special constructor that throws and error for us. There is the generic or you can send a special variation (example, SyntaxError, RangeError, etc.) by building off of something that’s already been defined. There are also DOM exceptions.
throw new Error()
Helps reduce the number of try/catch bloating your code.
Helps handle errors globally
Refactoring.guru here
mdn docs article on control flow and error handling here.
Fireship short with tips here
Caleb Curry here
w3Schools article here
Don’t overuse try/catch here (window.onerror)
Program with Erik here (error handler factory)