Catching browser errors in JavaScript can be done using a few different methods, each serving a specific use case. Here are the most common approaches:
1. **Try-Catch Block**: This is used for synchronous code. You wrap the code that might throw an error in a `try` block and handle the error in the `catch` block.
```javascript
try {
// Code that might throw an error
} catch (error) {
console.error(error);
// Error handling code
}
```
2. **Window Error Event Listener**: This method is used for catching unhandled errors globally, including those that occur in asynchronous code.
```javascript
window.addEventListener('error', function(event) {
console.error('Global error caught:', event.error);
// Error handling code
});
```
3. **Promise Rejection Handling**: For handling errors in promises, you use `.catch()` for individual promises or `window.addEventListener` for unhandled promise rejections.
```javascript
// Individual promise
somePromise()
.then(result => {
// Success handling
})
.catch(error => {
console.error(error);
// Error handling
});
// Global unhandled promise rejections
window.addEventListener('unhandledrejection', function(event) {
console.error('Unhandled promise rejection:', event.reason);
// Error handling code
});
```
4. **Async/Await with Try-Catch**: When using async functions, you can use a try-catch block to handle errors that occur in the awaited promises.
```javascript
async function someAsyncFunction() {
try {
let result = await somePromise();
// Success handling
} catch (error) {
console.error(error);
// Error handling
}
}
```
Each of these methods serves different scenarios, and often, a combination of them is used in a robust application to ensure all potential errors are appropriately caught and handled,