Middle
What error handling methods exist in JavaScript?
sobes.tech AI
Answer from AI
In JavaScript, there are several ways to handle errors:
- try...catch — the classic way to handle exceptions. Code that might throw an error is placed inside the
tryblock, and error handling is done in thecatchblock.
try {
// code that might throw an error
let result = riskyOperation();
} catch (error) {
console.error('An error occurred:', error);
}
- Error handling in promises — using
.catch()methods or the second argument of.then().
fetch('/api/data')
.then(response => response.json())
.catch(error => console.error('Request error:', error));
- async/await with try...catch — for asynchronous code, it's convenient to use
try...catchinsideasyncfunctions.
async function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
} catch (error) {
console.error('Error loading data:', error);
}
}
-
window.onerror and window.addEventListener('error') — global error handling in the browser.
-
Promise rejection handlers — handling unhandled promise rejections via
window.onunhandledrejection.
The choice of method depends on the context and the type of code (synchronous or asynchronous).