Error Handling in JavaScript
In programming, errors are inevitable. It's important to know how to properly catch and handle errors in JavaScript. In this article, we'll explore fundamental methods, from beginner to more advanced approaches.
We'll learn how to work with `try...catch` blocks, how to create custom errors, and how to handle asynchronous errors using Promises and async/await.
1. Handling Errors with `try...catch` Blocks
try { // Code that might throw an error const result = someUndefinedFunction(); }
catch (error) { console.error('Error:', error); }
Advantages of this method:
- Allows the program to continue execution after an error.
- Enables displaying user-friendly error messages.
2. Creating Custom Errors Using `throw`
function divide(a, b) { if (b === 0) { throw new Error('Cannot divide by zero'); } return a / b; }
try { divide(10, 0); } catch (error) { console.error(error.message); }
Advantages of this method:
- Allows creating specific error types for special cases in your program.
- Provides more precise and manageable error flow.
3. Handling Asynchronous Errors with Promises
fetch('https://some-api.com/data')
.then(response => { if (!response.ok) { throw new Error('Request failed'); } return response.json(); })
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Advantages of this method:
- Can handle multiple asynchronous errors simultaneously.
- Keeps code readable and manageable.
4. Handling Asynchronous Errors with `async/await`
async function getData() { try { const response = await fetch('https://some-api.com/data');
if (!response.ok) { throw new Error('Request failed'); }
const data = await response.json(); console.log(data); }
catch (error) { console.error('Error:', error); } }
getData();
Advantages of this method:
- Code is more similar to synchronous code in readability.
- Easier to manage nested asynchronous operations.