try-catch
blocks are the most basic structures used
for error handling in JavaScript.
try {
// code that may throw an error
} catch (error) {
// handle the error
}
function fetchData() {
return new Promise((resolve, reject) => {
try {
// Simulate an API call
setTimeout(() => {
const data = { id: 1, name: 'John Doe' };
resolve(data);
}, 1000);
} catch (error) {
reject(error);
}
});
}
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}