JavaScript Essentials - Advanced Error Handling
Advanced error handling techniques
Effective error handling is crucial for creating robust JavaScript applications. This tutorial covers advanced error handling techniques, including custom errors, error propagation, and asynchronous error handling.
Key Points:
- Use
try...catch
blocks to handle exceptions. - Create custom error types for specific error handling needs.
- Handle errors in asynchronous code using
async...await
andtry...catch
. - Log and propagate errors for better debugging and user experience.
Basic Error Handling
The basic way to handle errors in JavaScript is by using try...catch
blocks.
try {
// Code that may throw an error
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error);
}
Custom Errors
Creating custom error types can help you handle specific error conditions more effectively.
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
try {
throw new CustomError('This is a custom error');
} catch (error) {
if (error instanceof CustomError) {
console.error('Handled custom error:', error.message);
} else {
console.error('Unhandled error:', error);
}
}
Error Propagation
Error propagation involves catching an error and re-throwing it to be handled by another try...catch
block further up the call stack.
function functionA() {
try {
functionB();
} catch (error) {
console.error('Error caught in functionA:', error);
throw error; // Re-throw the error
}
}
function functionB() {
throw new Error('Error in functionB');
}
try {
functionA();
} catch (error) {
console.error('Error caught in global scope:', error);
}
Asynchronous Error Handling
Handling errors in asynchronous code can be challenging. Using async...await
with try...catch
provides a cleaner approach.
async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
Global Error Handling
For catching errors globally, you can use the window.onerror
event for synchronous errors and window.addEventListener('unhandledrejection')
for unhandled promise rejections.
window.onerror = function(message, source, lineno, colno, error) {
console.error('Global error handler:', error);
};
window.addEventListener('unhandledrejection', event => {
console.error('Unhandled promise rejection:', event.reason);
});
Logging and Monitoring
Logging errors to an external service or monitoring tool can help you track issues in production and improve the reliability of your application.
// Example using a hypothetical logging service
function logError(error) {
// Send error details to logging service
console.log('Logging error:', error);
}
try {
riskyOperation();
} catch (error) {
logError(error);
throw error; // Optionally re-throw the error
}
Summary
In this tutorial, you learned about advanced error handling techniques in JavaScript, including creating custom errors, propagating errors, handling errors in asynchronous code, and using global error handlers. Implementing these techniques can help you build more robust and maintainable applications.