Error Handling
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.
try { // Code that might throw an error const result = someUndefinedFunction(); }
catch (error) { console.error('Error:', error); }
Advantages of this method:
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:
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:
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: