In programming unintended side-effects called errors can and will happen in your code. Allowing these errors to be introduced to people that are using your programs is frowned upon and a very bad user experience.
Error Handling is the technique of smoothly handling these errors and providing useful information to a user.
Here are the important parts of error handling:Try
The try block allows you to try an initial blog of code.
async function doWork() { try {
let response = await fetch("www.worktobedone.com") let work = await response.json() return work
}}
To use Catch
To use the catch block allows you to catch an error from the initial blog of code.
async function doWork() { try {
let response = await fetch("www.worktobedone.com") let work = await response.json() return work
} catch(error) {
// Here we caught an error to alert
alert(error)
}}
Use Throw
To use the throw keyword allows you to control or create custom exceptions from your code.
async function doWork() { try {
let response = await fetch("www.worktobedone.com") let work = await response.json() return work
} catch(error) {
// Lets change the error output
throw new Error(`Oops we found this error during work - ${error}`)
}}
Conclusion
So finally block allows you to execute code regardless of errors in the try and catch blocks.
async function doWork() { try {
let response = await fetch("www.worktobedone.com") let work = await response.json() return work
} catch(error) {
throw new Error(`Oops we found this error during work - ${error}`)
} finally {
return "My work here is done."
}}
More error handling
This step by step tutorial showed the steps to using the try..catch…finally block to handle errors. If you enjoyed this post feel free to leave a comment about your thoughts and experiences handling errors in your code.