An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
How to work with error handling in Javascript
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 }}
Catch
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) }}
Throw
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}`) }}
Finally
The 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." }}
Let's chat about error handling
This walkthrough 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.
Happy Coding,
Terry Threatt
Original Link: https://dev.to/terrythreatt/how-to-work-with-error-handling-in-javascript-48dg
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To