If you’ve worked with JavaScript, you know errors are going to show up. It’s just part of coding. They’re annoying, but they can be handled. That’s what this guide is about—error handling and keeping your app running smoothly.
What Is Error Handling?
Error handling is how developers deal with things that go wrong in their code. Sometimes it’s small stuff like a typo. Other times, it’s big stuff that crashes everything. Either way, the idea is to catch those issues without crashing or having unexpected outcomes and report and manage them. When you get it right, your code is better, users are happier, and things just work.
Types of Errors You’ll See in JavaScript
- Syntax Errors
You typed something wrong. The computer can’t understand it. For example:
console.log("Hello World // oops, forgot a quote
Fix it: Check your typing. Tools like linters can help you spot mistakes faster.
- Runtime Errors
These errors pop up when your code is running. The code looks fine at first. Then—bam! It breaks.
console.log(myVariable.name); // What if `myVariable` doesn’t exist?
Solution: Use error-handling tools like try-catch
. Validate your variables before using them.
- Logical Errors
The program doesn’t crash. But the output is wrong.
function add(a, b) {
return a - b; // Wrong logic here
}
What to do: Test your code. Look at your logic step by step.
How to Handle Errors in JavaScript
Use try-catch
This is your go-to tool. You “try” some code. If it fails, you “catch” the error.
try {
let data = JSON.parse('{"name": "Alex"}');
console.log(data.name);
} catch (err) {
console.error("Oops! Something went wrong:", err.message);
}
Throw Your Own Errors
You can make your own custom error messages.
function divide(a, b) {
if (b === 0) throw new Error("Division by zero is not allowed.");
return a / b;
}
finally Block
Whether there’s an error or not, this part always runs.
try {
console.log("Starting something...");
} catch (error) {
console.log("Caught an error!");
} finally {
console.log("Done!");
}
Leveling Up: Advanced Error Tools
Custom Error Types
Build errors specific to your app by extending the Error
class.
class AppError extends Error {
constructor(message) {
super(message);
this.name = "AppError";
}
}
throw new AppError("This is a custom error.")
Promises and Errors
Handle errors in asynchronous code with .catch
.
fetch("https://example.com/api")
.then(response => response.json())
.catch(error => console.log("Something went wrong:", error));
Async/Await Error Handling
With try-catch
, managing async code gets easier.
async function fetchData() {
try {
let response = await fetch("https://example.com");
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Error fetching data:", error);
}
}
Tips for Error Handling in JavaScript
Log Everything
When you write code, errors will pop up. Logging them is key. Use console.log()
in development but switch to tools like Winston or Bunyan in production. These tools make it easier to track what went wrong and when.
Don’t Confuse Your Users
Errors like “TypeError: Cannot read property” confuse non-developers. Instead, display messages that explain what happened in plain language. For example, “Invalid email address. Please check and try again.” Your users will thank you.
Validate Inputs Immediately
Dirty data causes chaos. Always validate inputs before doing anything else. Use libraries like Joi to check things like data types, formats, and ranges. For example, confirm an age input is a number and not “twenty-five.”
Be Detailed, Not Cryptic
Avoid vague errors like “Operation failed.” Use specifics: “The file upload failed because it exceeded the 10MB limit.” This makes debugging faster and users less frustrated.
Fallback Mechanisms Are Your Friend
Code will break. Prepare for it. For example:
- If an API call fails, retry three times before giving up.
- Cache data locally and use it when the network is down.
- Default values can keep your app running when inputs are missing.
Group Errors Smartly
Logs can be overwhelming. Group related errors using error codes. For example, assign ERR_DB_CONN
for database issues and ERR_API_TIMEOUT
for network failures. When logs are organized, debugging becomes less painful.
Test the Worst-Case Scenarios
Don’t wait for users to find bugs. Test your app’s error handling during development. Simulate failures like API outages, invalid inputs, or corrupted files. Tools like Cypress or Jest can help automate this testing process.
Real-Time Monitoring
Catch errors before they snowball. Use error monitoring tools like Sentry or Rollbar. They send real-time alerts about issues, including stack traces and user details, so you can fix them quickly.
Explain Fixes to Users
Don’t just tell users what went wrong—guide them on how to fix it. If a password reset fails, say, “The email you entered is not registered. Please try again or sign up.”
Performance Issues Cause Errors Too
Slow apps create their own problems. Timeouts, unresponsive scripts, and crashes often come from poorly optimized code. Write efficient loops, use lazy loading, and minimize server requests.
Keep Documentation Ready
Every app should have an error-handling playbook. Document common errors, their causes, and troubleshooting steps. This helps new developers onboard quickly and keeps error handling consistent.
Helpful Tools for Debugging
- Browser Dev Tools: Fix errors in real time using the console.
- Sentry: Monitor and log errors in production apps.
- ESLint: Catch syntax issues early with this handy tool.
Conclusion
Errors don’t have to be scary. With the right tools and strategies, you can handle them like a pro. Learn the basics, practice with real-world examples, and stay calm when things break.
Previous Lesson
Next Lesson
Day 30: Deploying a Node.js Application