Handling errors effectively in JavaScript is not just about catching exceptions; it’s about understanding potential failure points, providing meaningful feedback, and maintaining a smooth user experience. In this blog, we’ll explore the different aspects of error handling in JavaScript, using vanilla-js and clear examples to help you grasp the concepts.
Errors in JavaScript can be broadly classified into two categories:
// This will throw a syntax error const name = 'Alice' console.log(name // Missing closing parenthesis
const person = null; console.log(person.name); // This will throw a runtime error: Cannot read properties of null
try...catch
StatementThe try...catch
statement allows you to handle exceptions gracefully. Code that might throw an error is placed inside the try
block, while the catch
block handles the error.
try { let result = riskyOperation(); console.log(result); } catch (error) { console.error("An error occurred:", error.message); }
In this example, if riskyOperation()
throws an error, the message will be logged without breaking the entire script.
catch
BlocksWith the use of block-scoped variables, you can define multiple catch
blocks by checking the type of error.
try { let data = JSON.parse("invalid json"); } catch (error) { if (error instanceof SyntaxError) { console.error("There was a syntax error:", error.message); } else { console.error("An unexpected error occurred:", error); } }
The finally
statement can be used after try...catch
to execute code regardless of an error being thrown. It’s useful for cleanup actions, such as closing database connections or releasing resources.
try { let result = riskyOperation(); console.log(result); } catch (error) { console.error("An error occurred:", error.message); } finally { console.log("Cleaning up!"); }
You can create your own error types by extending the Error
class. This gives you more control over error handling and allows for clearer error reporting.
class CustomError extends Error { constructor(message) { super(message); this.name = "CustomError"; } } try { throw new CustomError("Something went wrong!"); } catch (error) { console.error(`${error.name}: ${error.message}`); }
When working with the browser, it’s important to handle global errors as well. The window.onerror
event allows developers to catch unhandled errors at the window level, providing a way to log them centrally.
window.onerror = function(message, source, lineno, colno, error) { console.error(`Error occurred: ${message} at ${source}:${lineno}:${colno}`); }; // Example triggering an error nonExistentFunction(); // This will be caught by the window.onerror event
When working with asynchronous code using promises, proper error handling can be achieved using .catch()
or the async/await
syntax with try...catch
.
fetch("http://example.com/api/data") .then(response => { if (!response.ok) { throw new Error("Network response was not ok"); } return response.json(); }) .catch(error => { console.error("Fetch error:", error.message); });
async function fetchData() { try { const response = await fetch("http://example.com/api/data"); if (!response.ok) { throw new Error("Network response was not ok"); } const data = await response.json(); console.log(data); } catch (error) { console.error("Error fetching data:", error.message); } } fetchData();
By effectively using these error handling techniques in your JavaScript code, you can create resilient applications that handle potential failures gracefully while providing users with meaningful feedback. Familiarize yourself with these concepts and take your error handling skills to the next level!
22/10/2024 | VanillaJS
15/10/2024 | VanillaJS
14/09/2024 | VanillaJS
21/07/2024 | VanillaJS
14/09/2024 | VanillaJS
12/09/2024 | VanillaJS
22/10/2024 | VanillaJS
14/09/2024 | VanillaJS
14/09/2024 | VanillaJS
14/09/2024 | VanillaJS