Error handling in React JS
Course: React JS Training
Topic: Error handling
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Why error handling matters
Every web page you build is a conversation between your JavaScript and the browser. Sometimes that conversation goes wrong: a button points to an element that does not exist, a network request fails, or the user types text where a number was expected. Without error handling, a single mistake can stop your whole script, leaving a page with buttons that do nothing and no clue about what broke. With error handling, your program notices the problem, reports it in a controlled way, and keeps running.
This page teaches error handling as a browser skill: how JavaScript errors appear in the DevTools console, how the try...catch...finally structure works, how to create and throw your own errors, and how to handle failures in code that runs later, such as fetch requests. These are the same habits you will reuse in React, where uncaught errors can blank out a whole screen.
- A page without error handling fails silently: the user sees a broken page, the developer sees nothing.
- A page with error handling fails loudly and politely: the user sees a helpful message, the developer sees the real cause in the console.
2. What is an error, in simple words
An error is JavaScript's way of saying "I cannot continue with this instruction". When the browser hits an error, it creates an object that describes the problem, stops the current block of code, and hands that object upward until someone catches it. If nobody catches it, the browser prints a message in the console, such as Uncaught TypeError: Cannot read properties of undefined, and the rest of the current script does not run.
Think of it like a kitchen. If the milk is missing, a cook with good habits notices it at the start, tells the customer "we cannot make that dish today", and moves on to the next order. A cook without habits discovers the missing milk halfway through the recipe, throws everything down, and serves nobody. Error handling is the habit of checking early and reacting calmly.
Three everyday examples
- Reading a property of nothing:
document.querySelector(".cart").textContent when there is no element with class cart.
- Calling something that is not a function:
element.addEventListner("click", fn) with a misspelled method name.
- Turning bad text into data:
JSON.parse(">>") when the text is not valid JSON.
3. Key terms in error handling
These words appear in every error-handling discussion, so it helps to fix their meanings now.
- Exception: another name for an error while it is being passed around the program. "Throwing an exception" and "throwing an error" mean the same thing.
- Throw: to create an error and hand it to JavaScript with the
throw keyword.
- Catch: to receive a thrown error and deal with it inside a
catch block.
- Try block: the guarded section of code where errors are allowed to happen safely.
- Stack trace: the list of function calls that led to the error, printed in the console so you can retrace the path.
- Fallback: the plan B your code follows after an error, such as showing a saved copy of the data.
- Silent failure: the worst outcome, where an error happens, nothing is reported, and the program keeps pretending everything is fine.
Rule of thumb: an error should either be handled usefully or rethrown clearly. Never swallow an error with an empty catch block, because that turns a visible problem into an invisible one.
4. Types of errors in JavaScript
Not all mistakes are the same kind. It is useful to separate them, because each type is found and fixed in a different way.
| Type | What it means | When you meet it | Example |
| Syntax error | The code cannot even be read by the browser. | While loading the script, before anything runs. | Missing bracket: if (x === 1 { |
| Runtime error | The code is readable but an instruction fails while running. | While the page is running. | undefined.toFixed(2) |
| Logical error | The code runs without complaints but produces wrong results. | Any time; only testing and careful reading reveal it. | Using + to join a price and a tax instead of adding the numbers. |
Syntax errors are caught by the browser before your first line runs, so try...catch cannot protect you from them in the same script. Runtime errors are the ones try...catch is built for. Logical errors are not errors at all in JavaScript's eyes; only you can prevent them with tests and careful checks.
5. The try, catch and finally blocks
JavaScript wraps risky code in three connected blocks. The words are plain English: try this, catch any problem, and finally clean up no matter what happened.
try {
// Risky code goes here.
// If any line throws, the rest of this block is skipped.
} catch (error) {
// Runs only if something in the try block threw an error.
// "error" is the thrown object.
} finally {
// Runs always: after try success OR after catch.
// Used for cleanup such as hiding a loading spinner.
}
The rules of the structure
- The
try block is compulsory; you cannot write catch without a try before it.
- The
catch block is compulsory whenever you write try in classic form; finally is always optional.
- A shorthand
try {...} catch {...} without naming the error is allowed in modern browsers when you do not need the error details.
- You may combine
try and finally without catch, but then the error still spreads upward after the cleanup runs.
Here is the smallest useful example:
try {
console.log("Before the risk");
notDefined.toFixed(2);
console.log("After the risk"); // never runs
} catch (error) {
console.log("Caught:", error.message);
}
Output:
Before the risk
Caught: notDefined is not defined
The second console.log inside the try block is skipped, because execution jumps straight to the catch block the moment the error is thrown.
6. How try and catch work, step by step
Understanding the journey of an error makes the structure feel less like magic. Follow the order in which the browser executes things:
- The browser enters the
try block and runs its lines one by one.
- If every line succeeds, the
catch block is skipped completely, and finally runs next if it exists.
- If any line throws an error, JavaScript stops the
try block immediately at that line and creates an error object.
- That error object is passed as a parameter to the
catch block, which runs with it.
- After the
catch block finishes, finally runs (if present), and then the script continues normally after the whole structure.
- If the error happens inside a function called from the
try block, the error travels up from that function into the try block; you do not need the try inside the function itself.
The fourth point deserves a demonstration, because learners often think each function must guard itself:
function getFirstItem(list) {
return list[0].toUpperCase();
}
try {
console.log(getFirstItem([])); // list[0] is undefined
} catch (error) {
console.log("Handled outside:", error.message);
}
Output:
Handled outside: Cannot read properties of undefined (reading 'toUpperCase')
The error was born inside getFirstItem, but it was caught outside, in the caller. This "error bubbling" is why one well-placed try...catch around a whole feature is often better than scattering small try blocks everywhere.
7. The Error object
Everything JavaScript hands to your catch block is an object. The built-in Error object carries three useful pieces of information.
| Property | Type | What it holds |
name | String | The kind of error, such as "TypeError" or "RangeError". |
message | String | The human-readable description of the problem. |
stack | String | The stack trace: which function called which, line by line. |
try {
null.property;
} catch (error) {
console.log(error.name); // TypeError
console.log(error.message); // Cannot read properties of null (reading 'property')
console.log(error.stack); // full call path, file names and line numbers
}
You can also create your own error objects before throwing them, which is the key to meaningful messages:
const problem = new Error("Cart is empty");
console.log(problem.name); // Error
console.log(problem.message); // Cart is empty
In practice, most of your catch blocks will log error.message for the user-facing report and error.stack for debugging.
8. Throwing your own errors
Built-in errors only fire when JavaScript itself cannot continue. Your application has its own rules that JavaScript cannot guess: a username must not be empty, a quantity must be at least one, an API response must have the fields you expect. The throw keyword turns your rule violations into real, catchable errors.
function divide(total, count) {
if (count === 0) {
throw new Error("Cannot divide by zero items");
}
return total / count;
}
try {
console.log(divide(100, 4)); // 25
console.log(divide(100, 0)); // this line throws
console.log("never reached");
} catch (error) {
console.log("Problem:", error.message);
}
Output:
25
Problem: Cannot divide by zero items
What you are allowed to throw
throw new Error("message") is the recommended form: a proper object with name, message and stack.
throw new TypeError("message"), throw new RangeError("message") and similar built-in types let you label the kind of problem precisely.
throw "some text" technically works, because throw accepts any value, but a plain string has no stack, so debugging becomes harder. Avoid it.
Choosing a specific built-in type makes intent clearer:
function setQuantity(value) {
if (typeof value !== "number") {
throw new TypeError("Quantity must be a number");
}
if (value < 1) {
throw new RangeError("Quantity must be at least 1");
}
return value;
}
try {
setQuantity(0);
} catch (error) {
console.log(error.name, "-", error.message);
}
Output:
RangeError - Quantity must be at least 1
9. Built-in error types and when they appear
Knowing the common built-in error names helps you read console messages instantly and decide which ones your catch blocks should treat differently.
| Error type | Typical cause | Example that triggers it |
ReferenceError | Using a variable that has not been declared. | console.log(cartTotal); with no cartTotal anywhere. |
TypeError | Doing an operation on the wrong kind of value. | null.toFixed(2) or calling a misspelled method. |
RangeError | A value is outside the allowed range. | new Array(-5) or num.toFixed(101). |
SyntaxError | Text that should be code (or JSON) is malformed. | JSON.parse("{ bad json }"). |
URIError | A broken URI in encoding functions. | decodeURIComponent("%"). |
Note the difference in reach: a syntax error in your own script file stops the whole file from running, while a SyntaxError from JSON.parse happens at runtime and can be caught like any other error.
10. Rethrowing errors
Sometimes a function can handle some errors but not others. The clean pattern is: catch, check what you caught, handle what you can, and rethrow the rest so a higher level decides. Rethrowing means throwing the same error object again from inside the catch block.
function loadPrice(text) {
try {
const data = JSON.parse(text);
if (data.price === undefined) {
throw new TypeError("Response has no price field");
}
return data.price;
} catch (error) {
if (error instanceof SyntaxError) {
// We can handle this: return a safe default.
console.log("Bad JSON, using default price");
return 0;
}
// Anything else is not ours to fix: rethrow it.
throw error;
}
}
console.log(loadPrice('{"price": 199}')); // 199
console.log(loadPrice("not json at all")); // 0, handled
try {
loadPrice('{"name": "pen"}');
} catch (error) {
console.log("Escaped:", error.message); // Response has no price field
}
Output:
199
Bad JSON, using default price
Escaped: Response has no price field
The instanceof check lets one catch block behave like a sorting office: letters for this department are opened here, the rest are sent upstairs untouched.
11. Handling errors in asynchronous code
Code that runs later, such as network requests, does not report its errors to a normal try...catch placed in the wrong spot. The failure happens after your original function has already finished, so the error would be lost. Modern syntax solves this: inside an async function, awaiting a failing promise throws, and a regular try...catch catches it.
async function getUser(id) {
const response = await fetch("https://api.example.com/users/" + id);
if (!response.ok) {
throw new Error("Server responded with status " + response.status);
}
return response.json();
}
async function showUser() {
try {
const user = await getUser(1);
console.log(user.name);
} catch (error) {
console.log("Could not load user:", error.message);
}
}
showUser();
If the network fails or the server answers with an error status, the message Could not load user: ... appears instead of an uncaught promise rejection in the console.
The same handling looks different with promise chaining, where .catch() plays the role of the catch block:
fetch("https://api.example.com/users/1")
.then(function (response) {
if (!response.ok) {
throw new Error("Bad response " + response.status);
}
return response.json();
})
.then(function (user) {
console.log(user.name);
})
.catch(function (error) {
console.log("Could not load user:", error.message);
});
Both styles are correct; async/await with try...catch is usually easier to read, which is why it dominates modern code.
12. Errors the try block cannot see
Some errors escape ordinary handling, and a complete browser developer should know where they hide.
- Errors in code scheduled with
setTimeout or event handlers: a try...catch that schedules the callback does not guard what happens inside it. The callback needs its own try...catch, or the errors surface globally.
- Rejected promises nobody catches: if a promise fails and no
.catch() or await handles it, the browser reports an unhandled rejection.
- Global safety nets: the browser fires
window events for these escapees, letting you log them centrally.
// Last-resort listeners: useful for logging, not for fixing logic.
window.addEventListener("error", function (event) {
console.log("Uncaught error:", event.message);
});
window.addEventListener("unhandledrejection", function (event) {
console.log("Unhandled promise:", event.reason);
});
Use these listeners as a reporting layer in a real project, while still handling errors properly at the place where they happen. A global listener that only writes to the console is a safety net, not a strategy.
13. A realistic example: loading a profile with validation
The following example combines everything from this page into one small browser feature: a button loads a user profile from an API, checks the response, fills the page, and shows a friendly message on any failure. Read it from top to bottom; every rule from earlier sections appears here.
<button id="loadBtn">Load profile</button>
<p id="status"></p>
<script>
const button = document.getElementById("loadBtn");
const statusLine = document.getElementById("status");
function showStatus(text) {
statusLine.textContent = text;
}
async function loadProfile() {
showStatus("Loading...");
try {
const response = await fetch("https://api.example.com/profile");
if (!response.ok) {
throw new Error("Server said " + response.status);
}
const user = await response.json();
if (!user.name) {
throw new TypeError("Profile has no name field");
}
showStatus("Hello, " + user.name);
} catch (error) {
if (error instanceof TypeError) {
showStatus("The profile data is incomplete. Please try later.");
} else {
showStatus("Could not load your profile. Check your connection.");
}
console.log(error.stack); // full detail for the developer
} finally {
console.log("Profile load attempt finished");
}
}
button.addEventListener("click", loadProfile);
</script>
What this example demonstrates, step by step:
- The event listener itself contains no risky code; it simply calls the async function, so no error can escape from the scheduling step.
- The
try block covers both awaited calls, the two validation checks, and the success message.
- Each
throw uses a specific error type with a specific message, so the catch block can tell "our data is wrong" apart from "the network is down".
- The
catch block chooses a user-friendly message by type and logs the full stack for the developer.
- The
finally block runs in every outcome and is the correct place for cleanup such as removing a loading spinner.
14. Common mistakes and good habits
Most error-handling bugs in beginner projects come from a handful of repeated mistakes. Compare the two columns and audit your own code against the right-hand side.
| Mistake to avoid | Good habit to adopt |
Empty catch blocks that hide problems. | Always log the error or report it; never leave a catch block silent. |
| Catching everything in one huge block around the whole file. | Wrap each independent risky action, so one failure does not mask another. |
Using try...catch instead of validating input first. | Check values with plain conditions, and reserve try...catch for genuinely exceptional cases. |
| Trying to catch syntax errors of the same script file. | Fix syntax errors before shipping; they are found by the browser at load time. |
Placing try...catch around code that calls setTimeout and expecting it to guard the callback. | Put the guard inside the callback, because that is where the error will actually occur. |
Showing raw error.message text to users. | Show friendly messages to users and keep technical details in the console. |
| Throwing plain strings. | Throw new Error(...) or a specific built-in type so name and stack exist. |
One final habit ties this page together: when you open DevTools and see an uncaught error, resist the urge to paste a random try...catch over it. Read the message, find the line in the stack trace, decide whether the code should check the condition, handle the failure, or rethrow it, and then write the smallest block that expresses that decision. That reading-first approach is what separates error handling from error suppression, and it is the mindset the next part of this tutorial builds on with practice questions.
15. Custom error classes for real applications
Part 1 showed how to throw built-in errors. Real applications soon need their own vocabulary: a validation problem means "the user typed something wrong", while a network problem means "the server or connection failed". You can create such types with a class that extends the built-in Error. The call to super(message) sets up the standard message and stack properties, and you add whatever your app needs on top.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
class NetworkError extends Error {
constructor(message, status) {
super(message);
this.name = "NetworkError";
this.status = status;
}
}
function parseAge(text) {
const age = Number(text);
if (Number.isNaN(age)) {
throw new ValidationError("Age must be a number");
}
if (age < 1 || age > 120) {
throw new ValidationError("Age must be between 1 and 120");
}
return age;
}
try {
parseAge("abc");
} catch (error) {
if (error instanceof ValidationError) {
console.log("User problem:", error.message);
} else {
throw error; // not ours to handle
}
}
Output:
User problem: Age must be a number
instanceof checks become readable, so a catch block can route each error type to the right reaction.
- Extra fields such as
status travel with the error, giving the handler more context than a message string alone.
- The
name property makes console logs self-explanatory instead of showing the generic Error label.
16. A retry pattern for flaky network requests
Some failures are temporary: a weak mobile connection, a momentary server hiccup. Retrying the same request a limited number of times is a standard real-world answer. The helper below wraps fetch, remembers the last error, and gives up only after the allowed attempts are used.
async function fetchWithRetry(url, attempts = 3) {
let lastError;
for (let i = 0; i < attempts; i++) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
return await response.json();
} catch (error) {
lastError = error;
console.log("Attempt " + (i + 1) + " failed: " + error.message);
}
}
throw lastError;
}
A successful pass returns the parsed data immediately, so no extra requests are made; a failed pass is logged and the loop continues; if every pass fails, the last error is thrown to the caller, who decides what to do next.
Retry only failures that can plausibly fix themselves, such as timeouts or server errors. Retrying a request to a wrong address simply repeats the same mistake three times.
17. Graceful degradation: staying useful after a failure
Handling an error is not only about logging it. A mature page offers a fallback: cached data, sensible defaults, or an honest message. The pattern below combines the retry helper with a cache in localStorage; render and showBanner stand for your own display functions.
async function loadNews() {
try {
const data = await fetchWithRetry("https://example.com/api/news");
localStorage.setItem("newsCache", JSON.stringify(data));
render(data);
} catch (error) {
const cached = localStorage.getItem("newsCache");
if (cached) {
render(JSON.parse(cached));
showBanner("Showing saved news because the network is unavailable.");
} else {
showBanner("News is unavailable right now. Please try again later.");
}
}
}
The reader now sees content in three of the four possible outcomes: fresh data, cached data, or a clear message. Only a page with no handling at all shows a blank box and a silent console.
18. Common mistakes in real projects, with fixes
Part 1 listed beginner habits to avoid. The mistakes below appear once projects grow larger; each is shown with the corrected version.
Calling async functions without await inside try
function saveSettings() {
return Promise.reject(new Error("Storage full"));
}
// Wrong: no await, so the rejection is not caught here.
try {
saveSettings();
console.log("Saved!");
} catch (error) {
console.log("This line never runs");
}
// Correct: await inside an async function.
async function applySettings() {
try {
await saveSettings();
console.log("Saved!");
} catch (error) {
console.log("Save failed:", error.message);
}
}
applySettings(); // logs: Save failed: Storage full
Branching on the error message text
Messages are written for humans and change often; types are written for code and stay stable.
function checkQuantity(value) {
if (value < 1) {
throw new RangeError("Quantity must be at least 1");
}
}
try {
checkQuantity(0);
} catch (error) {
if (error instanceof RangeError) { // correct: check the type
console.log("Please enter a larger amount.");
} else {
throw error;
}
}
Doing cleanup only inside the try block
let spinnerOn = false;
async function run() {
try {
spinnerOn = true;
await Promise.reject(new Error("network down"));
spinnerOn = false; // skipped, because the line above throws
} catch (error) {
console.log("Failed:", error.message);
} finally {
spinnerOn = false; // always runs
}
console.log("Spinner cleared:", !spinnerOn);
}
run();
Output:
Failed: network down
Spinner cleared: true
Returning a value from finally
function risky() {
try {
throw new Error("real problem");
} finally {
return "all good"; // a return here swallows the error
}
}
console.log(risky()); // "all good" — the error has vanished
The correct way: never return from finally. Use that block only for cleanup and let errors flow.
Replacing the original error and losing its details
// Wrong: the new error hides what actually happened.
throw new Error("Something went wrong");
// Correct: keep the cause visible for debugging.
throw new Error("Could not read settings: " + error.message);
19. Best practices for production code
- Validate early with plain conditions; reserve
try...catch for operations that can genuinely fail, such as parsing, network calls and storage access.
- Throw specific error types with specific messages, and prefer custom classes for application-level categories.
- Handle errors at the level that can actually react: low-level helpers rethrow, user-interface code catches and shows a message.
- Never leave a
catch block empty; log at minimum, and rethrow what you cannot handle.
- Show friendly text to users; keep
name, message and stack for the console or a logging service.
- Put cleanup in
finally: hide spinners, re-enable buttons, clear timers.
- Prefer
await with try...catch for async flows, so logic and its failures read top to bottom.
- Add global
error and unhandledrejection listeners as a reporting safety net, never as the main strategy.
- Test failure paths on purpose: go offline in DevTools, submit bad input, point a request at a wrong URL.
- Keep functions small and single-purpose, so each
try block guards one clear operation.
20. Practical project: a resilient quote card
Goal: a small page that loads a quote from an API, caches it, and survives every failure mode — server error, network down, first visit with no cache. Save the file below and open it in a browser.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Resilient quote card</title>
</head>
<body>
<p id="quote">Press the button to load a quote.</p>
<p id="status"></p>
<button id="loadBtn">Load quote</button>
<script>
const quoteBox = document.getElementById("quote");
const statusLine = document.getElementById("status");
const loadBtn = document.getElementById("loadBtn");
const offlineQuotes = [
"Errors are teachers in disguise.",
"Read the message before writing the fix.",
"Small daily practice beats long cramming."
];
function showQuote(text, source) {
quoteBox.textContent = '"' + text + '"';
statusLine.textContent = "Source: " + source;
}
async function loadQuote() {
loadBtn.disabled = true;
statusLine.textContent = "Loading...";
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts/1"
);
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
const post = await response.json();
if (typeof post.title !== "string" || post.title.length === 0) {
throw new TypeError("Response has no title");
}
localStorage.setItem("lastQuote", post.title);
showQuote(post.title, "network");
} catch (error) {
const saved = localStorage.getItem("lastQuote");
if (saved) {
showQuote(saved, "saved copy (network failed)");
} else {
const randomIndex = Math.floor(Math.random() * offlineQuotes.length);
showQuote(offlineQuotes[randomIndex], "offline list (network failed)");
}
console.log("Load failed:", error.name, "-", error.message);
} finally {
loadBtn.disabled = false;
}
}
loadBtn.addEventListener("click", loadQuote);
</script>
</body>
</html>
How the pieces work together
- The
try block performs the only risky operations, the two awaited calls, and validates the data before using it.
- The
catch block never shows technical text to the user; it picks the best fallback, the cached copy first and the built-in list second, while the full details go to the console for the developer.
- The
finally block re-enables the button in every outcome, so the page can never get stuck.
- Every successful load also writes to
localStorage, which is what makes the next failure less painful.
Testing the failure paths
- Open DevTools, switch the Network tab to Offline, reload, and click the button: the source label should say the network failed.
- Temporarily change the validation condition so it always throws: the fallback should still appear, proving the catch block works for data problems too.
- Restore the code and confirm the normal path shows
Source: network again.
21. Practice Exercises
- Write
safeDivide(a, b) that throws a RangeError when b is zero, and a caller that catches it and prints a friendly message.
- Read a value from
localStorage, parse it with JSON.parse inside try...catch, and return a default object when the stored text is corrupted.
- Create a
ValidationError class and a setUsername(text) function that throws it for empty or overly long names; catch the error in a form handler and show the message in a paragraph.
- Add a retry loop of three attempts to a
fetch helper and log the attempt number each time a request fails.
- Demonstrate
finally: show a "Loading..." status line, then clear it in finally whether the operation succeeded or failed.
- Register listeners for
error and unhandledrejection on window, then trigger both kinds of failure on purpose and watch the console.
- Find a function whose
finally block contains a return, explain why its errors disappear, and rewrite it so the error survives.
22. Interview Questions and Answers
What is the difference between a syntax error and a runtime error?
A syntax error is detected while the browser reads the file, before any line runs, and it stops the whole script; a missing bracket is the classic case. A runtime error happens while the code executes, for example reading a property of undefined, and it can be caught with try...catch.
Why does a try block not catch errors thrown inside setTimeout callbacks?
The callback runs later, from the browser's task queue, long after the try block has finished executing. An error is handled by the try block that is active at the moment it is thrown, so the callback needs its own try...catch inside it.
When does the finally block run?
Always, once the structure has been entered: after a successful try, after the catch block handles an error, and even when the try block contains a return. That guarantee is exactly why cleanup code belongs there.
What happens if you return a value from the finally block?
The return replaces any pending result or error: an error about to be thrown is swallowed and the function ends normally. For this reason finally should contain only cleanup statements, never return or throw.
What is the difference between ReferenceError and TypeError?
A ReferenceError means the name itself was not found, usually an undeclared variable. A TypeError means the value was found but used wrongly, such as calling toFixed on a string or reading a property of null.
Why prefer throw new Error over throwing a string?
An Error object carries name and stack, so logs show what kind of problem occurred and where. A thrown string has neither, which makes debugging painful and makes instanceof checks in catch blocks impossible.
How does an error travel through nested function calls?
The function where the error is thrown stops immediately, and the error propagates up the call stack, giving each caller a chance to catch it. The first try...catch on the way up handles it; if none exists, the browser reports it as uncaught.
How do you handle errors with async/await compared with promise chaining?
With async/await, a rejected promise throws at the await line, so a normal try...catch around it works. With chaining, a final .catch() receives any error from any earlier step. Both are correct; async/await usually reads more clearly.
What is an unhandled promise rejection?
A promise that rejected with no .catch() and no await handling it. The browser reports it in the console and fires the unhandledrejection event on window, which you can listen to for central logging.
When should a catch block rethrow an error?
When it can handle only part of the situation. A function might turn a SyntaxError into a default value but has no idea what to do with a network failure, so it rethrows and lets a higher level decide. Rethrowing keeps responsibility in the right place.
Why are empty catch blocks dangerous?
They convert a visible failure into an invisible one: the program continues with missing data or broken state, and neither user nor developer is told. If a catch block genuinely must ignore an error, it should still log it and explain in a comment why ignoring is safe.
How do custom error classes help a team?
They give the application a shared vocabulary: instanceof checks read like sentences, extra fields such as a status code travel with the error, and the name in logs instantly shows which subsystem failed. The benefit grows with the size of the project and the team.
23. Quick Revision Checklist
try guards risky code, catch receives the error object, finally always runs and is for cleanup.
- The error object exposes
name, message and stack.
- Throw with
throw new Error("...") or a specific type such as TypeError or RangeError.
- Runtime errors can be caught; syntax errors of the same file cannot.
- Errors bubble up the call stack until the first catch block handles them.
- Rethrow what you cannot handle; never leave a catch block empty.
- Branch with
instanceof, never by comparing message text.
- In async functions put
await inside try; in promise chains end with .catch().
- Uncaught errors and unhandled rejections fire
error and unhandledrejection on window.
- Never
return from finally; it swallows errors.
- Custom classes extending
Error give your app named, typed errors with extra fields.
- Retry only self-healing failures, and always provide a fallback for the user.
- Test failure paths deliberately: offline mode, bad input, wrong URLs.
24. Official Documentation and Further Reading
The research compiled for this course did not confirm a dedicated official documentation address for JavaScript error handling, so this section points only to pages from the course's curated reading list that extend these ideas into the React part of your training.
Conclusion
Error handling is the difference between a page that breaks quietly and an application that fails gracefully. You now know how to guard code with try...catch...finally, how to throw and classify errors with built-in and custom types, how to route failures through rethrowing and instanceof, and how to keep asynchronous flows safe with await inside try blocks. You have also seen the real-world patterns that users actually feel: retries, caches, fallbacks and honest messages.
Carry one mindset forward: read the error before reacting to it, handle what you can where you can, and never hide what you cannot fix. When you reach the React module, these same ideas reappear at the component level, where errors in rendering and data fetching must be caught deliberately so one failing part does not take down the whole screen. The syntax changes slightly; the discipline you built on this page does not.
Learn more in the React JS Training course, or register for a course demo.