JavaScript Error Handling
JavaScript Error Handling
JavaScript error handling is a critical part of writing robust applications. It helps developers manage and respond to unexpected conditions or exceptions that occur during code execution, ensuring that the application doesn't crash or behave unpredictably.
Error Types in JavaScript
JavaScript has built-in error types that can be handled using error-handling mechanisms:
- SyntaxError: Errors in the syntax of the code.
- ReferenceError: Occurs when a non-existent variable is referenced.
- TypeError: Happens when a value is not of the expected type.
- RangeError: Raised when a number is outside its allowed range.
- URIError: Thrown when invalid parameters are passed to URI handling functions.
Mechanisms for Error Handling
1. try...catch Block
The try...catch
block is used to handle runtime errors. Code that might throw an error is placed in the try
block, and the catch
block handles the error if one occurs.
Example:
try { let result = 10 / 0; // This is not an error in JavaScript but let's add a condition if (!isFinite(result)) { throw new Error("Division by zero is not allowed."); } console.log(result); } catch (error) { console.error("Error occurred:", error.message); } finally { console.log("Execution complete."); }
Explanation:
try
: The risky operation is placed here.catch
: The error is caught and handled.finally
: Code that always executes regardless of whether an error occurred or not.
2. Custom Error Handling
You can throw custom errors using the throw
keyword.
Example:
function checkAge(age) { if (age < 18) { throw new Error("You must be at least 18 years old."); } return "Access granted."; } try { console.log(checkAge(15)); } catch (error) { console.error("Caught an error:", error.message); }
Explanation:
- The function checks if the age is less than 18 and throws a custom error if the condition is true.
- The
try...catch
block ensures the program doesn’t crash.
3. Promise and async/await Error Handling
For asynchronous operations, errors can be handled using .catch()
for Promises or try...catch
for async/await
.
Example using Promises:
let promise = new Promise((resolve, reject) => { let success = false; if (success) { resolve("Operation successful."); } else { reject("Operation failed."); } }); promise .then(response => console.log(response)) .catch(error => console.error("Promise error:", error));
Example using async/await
:
async function fetchData() { try { let response = await fetch("https://jsonplaceholder.typicode.com/posts"); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } let data = await response.json(); console.log(data); } catch (error) { console.error("Error fetching data:", error.message); } } fetchData();
4. Error Object
When an error is thrown, JavaScript creates an Error
object with properties like:
message
: Describes the error.name
: Type of the error.stack
: Stack trace.
Example:
try { throw new Error("Custom error message"); } catch (error) { console.log("Name:", error.name); // "Error" console.log("Message:", error.message); // "Custom error message" console.log("Stack:", error.stack); // Stack trace }
5. Using onerror for Global Error Handling
The window.onerror
event is used to catch errors that occur anywhere in the application.
Example:
window.onerror = function (message, source, lineno, colno, error) { console.error("Global error caught:", message, "at", source, "line", lineno); }; // Simulate an error nonExistentFunction();
Best Practices
- Specific Error Handling: Catch specific errors instead of using a generic
catch
block. - Don’t Swallow Errors: Always log or handle errors instead of ignoring them.
- Fallback Mechanisms: Provide fallback solutions for recoverable errors.
- Avoid Using
try...catch
Excessively: Only use it where necessary to avoid performance overhead.
Error handling in JavaScript ensures that your applications remain robust and user-friendly even when issues arise.