π¨ How to Handle Unhandled Exceptions & Unhandled Promise Rejections in JavaScript and React
One of the biggest differences between a demo app and a production app is error handling.
A good application doesn't just work when everything is fineβit fails gracefully when something goes wrong.
π§ 1οΈβ£ What is an Unhandled Exception?
An unhandled exception is an error that is thrown but never caught.
Example:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
divide(10, 0); // β Uncaught Error
Since there's no try...catch, the application may crash or stop executing that code path.
β
Handle It with try...catch
try {
divide(10, 0);
} catch (error) {
console.error(error.message);
}
β Prevents the app from crashing unexpectedly.
π§ 2οΈβ£ What is an Unhandled Promise Rejection?
When a Promise rejects and no .catch() (or try...catch with await) handles it.
fetch("/api/users")
.then(res => res.json());
// β No .catch()
Or:
async function getUsers() {
const res = await fetch("/api/users");
return res.json();
}
// β No try...catch
β Handle Async Errors Properly
async function getUsers() {
try {
const res = await fetch("/api/users");
if (!res.ok) {
throw new Error("Failed to fetch users");
}
return await res.json();
} catch (error) {
console.error(error);
}
}
βοΈ 3οΈβ£ Handling Errors in React
React Error Boundaries catch:
β Rendering errors
β Lifecycle errors
β Constructor errors
Example:
<ErrorBoundary>
<Dashboard />
</ErrorBoundary>
π¨ Error Boundaries DO NOT Catch
β Event handler errors
<button onClick={() => {
throw new Error("Boom");
}} />
β Async errors
setTimeout(() => {
throw new Error("Boom");
}, 1000);
β Promise rejections
You must handle these yourself.
π 4οΈβ£ Global Error Handling (Browser)
You can listen for uncaught JavaScript errors:
window.addEventListener("error", (event) => {
console.error("Unhandled Exception:", event.error);
});
Useful for:
- Logging
- Monitoring
- Crash reporting
π 5οΈβ£ Global Promise Rejection Handling
Handle promises that nobody caught:
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled Promise:", event.reason);
});
This is commonly used to send errors to monitoring tools.
π 6οΈβ£ Log Errors to Monitoring Services
In production, don't just use:
console.error(error);
Use tools like:
- Sentry
- Bugsnag
- Datadog
These provide:
β Stack traces
β User sessions
β Browser info
β Release tracking
π¨ Common Mistakes
β Empty catch blocks
try {
// code
} catch {}
π Silently ignores errors.
β Swallowing errors
catch (error) {
// do nothing
}
Always log or handle them appropriately.
β Assuming fetch() throws for HTTP errors
const res = await fetch("/users");
A 404 or 500 does not throw. You should check:
if (!res.ok) {
throw new Error("Request failed");
}
π‘ Senior-Level Insight
A good error-handling strategy has multiple layers:
-
Local handling:
try...catchfor recoverable operations. - Component handling: Error Boundaries for UI rendering errors.
-
Global handling:
window.onerrorandwindow.onunhandledrejection. -
Monitoring: Send errors to a centralized service instead of relying on
console.error.
The goal isn't to hide errorsβit's to capture them, recover when possible, and give users a graceful experience.
π― Interview One-Liner
Handle synchronous exceptions using
try...catch, asynchronous errors using.catch()ortry...catchwithasync/await, use React Error Boundaries for rendering errors, and implement global error listeners and monitoring tools to capture uncaught exceptions and promise rejections in production.
JavaScript #ReactJS #Frontend #ErrorHandling #WebDevelopment #InterviewPrep #EngineeringMindset #SoftwareEngineering
United States
NORTH AMERICA
Related News
What a Night of Work Looks Like From Inside the Machine
4h ago
Webhooks vs. Polling APIs: Which Architecture Should You Choose?
4h ago
Dead-Letter Queues for Webhooks: Safe Replay, Idempotency, and Monitoring
1d ago
Discovery: How an Agent Finds Your APIs
1d ago
Secret Claude Tracker Shocks Users After Anthropic's Anti-Surveillance Stance
1d ago