Error handling in JavaScript is crucial for writing robust and reliable code. There are several mechanisms and best practices for handling errors effectively:
- try...catch Statement: Used to handle exceptions (errors) that occur within a block of code. The syntax is as follows:
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
}
Here's an example:
try {
let result = someFunctionThatMayThrowAnError();
console.log(result);
} catch (error) {
console.error('An error occurred:', error);
}
throw Statement: Used to generate an exception manually. You can throw any JavaScript value (object, string, number, etc.):
function validateInput(input) {
if (!input) {
throw 'Input cannot be empty';
}
// Other validation logic
}
Error Object: JavaScript has built-in error types like
Error
, SyntaxError
, ReferenceError
, TypeError
, etc. You can create custom error objects by extending the Error
constructor:class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
throw new CustomError('Something went wrong');
Global Error Handling: You can use the
window.onerror
event handler or window.addEventListener('error', handler)
to capture unhandled errors globally:window.onerror = function(message, source, lineno, colno, error) {
console.error('Global error:', message, source, lineno, colno, error);
};
Promises Error Handling: When working with Promises, you can use the
.catch()
method to handle errors:fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Async/Await Error Handling: When using async functions with the
async
and await
keywords, you can use try...catch
for error handling:async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
- Logging: Always log errors appropriately, either to the console or a logging service, to aid in debugging and monitoring applications in production.
Remember to handle errors gracefully to provide a better user experience and make your code more resilient.
0 Comments