Skip to main content

2 posts tagged with "Error Handling"

View All Tags

Unhandled Promise Rejections in JavaScript: How to Catch the Errors Your Users Never Report

Published: · 9 min read
Robin Alex Panicker
Cofounder and CPO, Appxiom

An unhandled promise rejection is the quietest way a web app can break. A request fails, an async function throws, and nothing on screen tells the user what happened. The button just stops working, the spinner never ends, or the form submits nothing. Most users will not file a bug report. They reload, try once more, and leave. This post explains why these errors slip past the usual safety nets, how to catch every one of them in the browser, and how to find the code that caused them once they show up in production.

Prerequisites​

The code in this post runs as written with:

  • Any current version of Chrome, Edge, Firefox or Safari. The unhandledrejection event is supported in all of them.
  • Node.js 18 or later for the Node behavior described later in the post.
  • typescript-eslint with type-aware linting enabled for the no-floating-promises rule.
  • The Appxiom Web SDK (npm install @appxiom/web) if you want rejections captured with their activity trail. Setup steps are in the Web SDK installation guide.

What an unhandled promise rejection is​

A promise rejection is unhandled when a promise rejects and no .catch() handler or try/catch around an await is attached to it by the time the browser finishes its current round of microtasks. The browser then reports it, and in Chrome's console it looks like this:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')
at loadProfile (profile.js:14:28)

The important word is "in promise". The error did not stop your script the way a synchronous throw would. The code that started the async work has already returned, so execution carries on, and the only trace is a console line that nobody in production will ever see.

Why try/catch and window.onerror miss it​

Most teams have a global window.onerror handler and wrap risky code in try/catch. Neither of them sees a rejected promise in the common cases.

try/catch only catches a rejection when you await the promise inside the try block. Call an async function without await and the rejection escapes:

async function saveSettings(settings) {
const res = await fetch('/api/settings', {
method: 'POST',
body: JSON.stringify(settings),
});
return res.json();
}

try {
saveSettings(form); // no await: the rejection happens later, outside this block
} catch (err) {
showError(err); // never runs
}

window.onerror and the error event cover uncaught synchronous exceptions and resource load failures. Promise rejections go to a separate event, unhandledrejection, so an error dashboard built only on onerror has a blind spot exactly where modern async code lives.

The five patterns that cause most unhandled rejections​

In real codebases the same few patterns show up again and again.

PatternWhat goes wrongFix
Fire and forget callsAn async function is called from an event handler without await or .catch()Await it inside a try/catch, or chain .catch()
.then() without .catch()The chain has no rejection handler at the endEnd every chain with .catch()
Promise.allOne rejected promise rejects the whole callHandle it, or use Promise.allSettled
Async callbacks in forEachforEach ignores the returned promisesUse for...of with await, or Promise.all with map
Parsing the responseres.json() rejects with a SyntaxError when the server returns HTML or an empty bodyCheck res.ok and the content type before parsing

Two of these deserve a closer look because they surprise even experienced developers.

fetch does not reject on HTTP errors​

fetch resolves for any response the server sends, including a 404 or a 500. It rejects only when the request itself fails, for example on a network error, a CORS failure or an aborted request. So a 500 that returns an HTML error page sails through the fetch call and then rejects one line later in res.json():

// Before: a 500 with an HTML body becomes "Unexpected token '<'"
async function loadOrders() {
const res = await fetch('/api/orders');
return res.json();
}

// After: fail early with an error that says what happened
async function loadOrders() {
const res = await fetch('/api/orders');
if (!res.ok) {
throw new Error(`GET /api/orders failed with ${res.status}`);
}
return res.json();
}

The fixed version still throws, but it throws an error that names the endpoint and the status code. That turns a confusing SyntaxError in your logs into something you can act on.

Async loops that nobody awaits​

forEach does not wait for async callbacks, so any rejection inside them becomes unhandled:

// Before: three requests start, nobody waits, failures go unhandled
items.forEach(async (item) => {
await uploadItem(item);
});

// After: wait for every upload and handle failures in one place
const results = await Promise.allSettled(items.map((item) => uploadItem(item)));
const failed = results.filter((r) => r.status === 'rejected');
if (failed.length > 0) {
reportUploadFailures(failed.map((r) => r.reason));
}

Promise.allSettled waits for every promise and never rejects, so you decide what a partial failure means for the user instead of losing it.

How to catch every unhandled rejection with unhandledrejection​

The browser fires an unhandledrejection event on window for each rejection that reaches the end of its microtask turn without a handler. Listening for it gives you a single place to log what your local handlers missed:

window.addEventListener('unhandledrejection', (event) => {
const reason = event.reason;
const message = reason instanceof Error ? reason.message : String(reason);
const stack = reason instanceof Error ? reason.stack : undefined;

sendToLogging({
type: 'unhandledrejection',
message,
stack,
url: window.location.href,
});
});

A few details matter here:

  • event.reason is whatever the promise rejected with. If code calls reject('timeout') with a plain string, you get no stack trace at all. Always reject with an Error object.
  • Calling event.preventDefault() stops the browser from printing the default console message. Leave it out while you are still debugging.
  • A rejectionhandled event fires if a handler is attached to the same promise later. It is rare in practice, but it explains the odd case where a rejection is logged and then handled anyway.

In Node.js the default is stricter. Since Node 15 an unhandled rejection crashes the process, which is why server code tends to get fixed faster than browser code. In the browser nothing crashes, so the bug can live in production for months.

Why the global handler is only the start​

A global listener tells you that a rejection happened. It rarely tells you why. A message such as TypeError: Failed to fetch with a stack that ends inside a bundled vendor file says very little about which user action triggered it, which API call was in flight or whether it actually stopped anyone from finishing what they came to do.

That missing context is the expensive part. Here is an illustrative case. A checkout page logs a few hundred Failed to fetch rejections a day. The team assumes flaky mobile networks and moves on. The real cause is a payment config request that times out on one browser after a release, and every one of those rejections is a customer who could not pay. The count alone looked harmless. The journey it broke was not.

Find the rejections that cost you users. The Appxiom Web SDK captures errors automatically, including unhandled promise rejections, and records the activity trail and network calls around each one. Connect your coding agent to the Appxiom MCP server and ask: "Check Appxiom for the most frequent JavaScript errors and unhandled promise rejections on the web app." The agent gets the list with occurrence telemetry, and you decide which one to fix first.

Appxiom maps issues to the goals you define, such as checkout or sign up, and scores them with Goal Friction Impact. A rejection that fires on every page load but never blocks a goal ranks below one that stops payments. If you have not set goals up before, our post on Goal Friction Impact and the revenue cost of broken user journeys explains the idea, and session replay vs activity trail covers why a timestamped trail is often faster to debug from than a video.

A checklist for promise error handling​

Use this list in code review. Each item closes one of the gaps above.

  1. Every promise is either awaited inside try/catch or ends in .catch().
  2. Event handlers that call async functions handle their own errors, because nothing above them will.
  3. fetch calls check res.ok before reading the body.
  4. Code rejects with Error objects, never plain strings or objects, so every rejection has a stack.
  5. Parallel work uses Promise.allSettled when a partial failure is acceptable, and Promise.all only when one failure should cancel everything.
  6. Async loops use for...of with await or Promise.all over map, never forEach.
  7. A global unhandledrejection listener sends anything that slips through to your monitoring.
  8. Lint rules such as @typescript-eslint/no-floating-promises flag unawaited promises before they ship.

The lint rule is worth turning on even in a large existing codebase. It needs type information to run, and the first pass usually finds dozens of fire and forget calls, most of which are fine and some of which are the bug you have been chasing.

Catch them before your users give up​

Unhandled promise rejections are not exotic bugs. They come from a handful of everyday patterns, and each one has a direct fix. What makes them costly is that the browser keeps running, so nobody notices until a metric drops. Fix the patterns in review, add a global listener as a safety net, and track rejections against the journeys they interrupt so the one that blocks checkout never hides behind the ones that do not matter. Coding agents can do much of the fixing once they can see that production data, as we wrote in your AI coding agent can write the fix, but it can't see production.

To start capturing unhandled rejections from your own web app, follow the Appxiom Web SDK quickstart. It takes one npm install and a single init call.

Implementing Custom Error Boundaries for Robust Flutter UI Failures

Published: · 5 min read
Sandra Rosa Antony
Software Engineer, Appxiom

In mobile engineering, application reliability is more than just a buzzword-it's a non-negotiable expectation for users and businesses. When a Flutter app faces an unexpected UI failure, leaving users stranded with a blank screen or a hard crash damages trust and complicates both debugging and observability. To build truly robust Flutter apps, it's critical to capture, contain, and report these failures gracefully. This post dives deep into implementing custom error boundaries in Flutter, focusing on real-world engineering challenges around performance, debugging, observability, and reliability.


Why UI Failures Are a Real-World Challenge​

Although Flutter provides a global FlutterError.onError handler and general crash reporting options, many production bugs are:

  • Component-specific and intermittent: UI crashes triggered by edge case state or data inconsistencies.
  • Hard to reproduce: Failures in a specific widget tree context or caused by rare user behavior.
  • Invisible until too late: Resulting in a bad user experience, with little feedback or in-app traceability.

These issues underline the need for component-scoped error boundaries-an established pattern in web frameworks like React, but not natively supported in Flutter.


1. Understanding Error Boundaries in Flutter​

Flutter's ErrorWidget replaces malfunctioning widgets on build errors, but global error handlers (FlutterError.onError and runZonedGuarded) often lack context and granularity. A custom error boundary lets you:

  • Capture errors at the widget level instead of the entire application.
  • Display fallback UIs rather than a generic red screen or crash.
  • Report contextual information upstream for debugging and observability.

Let's implement a robust, reusable error boundary widget:

import 'package:flutter/material.dart';

typedef ErrorLogger = void Function(FlutterErrorDetails details);

class ErrorBoundary extends StatefulWidget {
final Widget child;
final Widget Function(FlutterErrorDetails)? fallbackBuilder;
final ErrorLogger? onError;

const ErrorBoundary({
Key? key,
required this.child,
this.fallbackBuilder,
this.onError,
}) : super(key: key);

@override
State<ErrorBoundary> createState() => _ErrorBoundaryState();
}

class _ErrorBoundaryState extends State<ErrorBoundary> {
FlutterErrorDetails? _errorDetails;

@override
void initState() {
super.initState();
_errorDetails = null;
}

@override
Widget build(BuildContext context) {
if (_errorDetails != null) {
if (widget.fallbackBuilder != null) {
return widget.fallbackBuilder!(_errorDetails!);
}
return Center(child: Text('Oops! Something went wrong.'));
}

try {
return widget.child;
} catch (error, stack) {
final details = FlutterErrorDetails(exception: error, stack: stack);
setState(() {
_errorDetails = details;
});
widget.onError?.call(details);
return SizedBox.shrink(); // Prevents crash; fallback UI in next build.
}
}
}

Usage example:

ErrorBoundary(
child: SomeComplexWidget(),
fallbackBuilder: (details) => ErrorFallbackWidget(details: details),
onError: (details) {
// Send to your observability platform
},
)

2. Performance Implications and Optimization Tips​

Implementing error boundaries introduces new code paths into your widget tree. To keep performance tight:

  • Scope boundaries surgically: Don’t wrap your entire app tree; target complex or third-party widgets, dynamic content, or historically flaky areas.
  • Avoid excessive setState: Only trigger state updates on actual errors, not on every frame.
  • Profile render times: Use flutter devtools to monitor how the error boundary affects build performance, especially in large lists or trees.
  • Cache fallback widgets: If your fallback UI is expensive to build, create it once and reuse.

Remember, the overhead of catching errors is far less costly than the damage of an unhandled crash.


3. Debugging Strategies with Error Context​

Catching exceptions at the widget boundary level gives valuable debugging signal:

  • Full error details: The FlutterErrorDetails object includes the stack trace, exception, and the library.

  • Widget context: You can enrich the error log by including widget-specific data or state, for example:

    onError: (details) {
    final widgetName = context.widget.runtimeType.toString();
    sendLogToCrashlytics('Error in $widgetName', details);
    }
  • Reproducibility: Log local state values, user actions, or navigation stack at the failure point for better traceability.

Practical Tips:​

  • Integrate with log aggregators (e.g., Sentry, Crashlytics) that support custom metadata and breadcrumbs.
  • Use distinct error boundary widgets for different app sections to localize errors.
  • Provide developer-centric fallback UIs in debug mode that include stack traces or error types.

4. Observability: Actionable Error Reporting​

Handling the error isn’t enough-you must see it in the wild and measure impact:

Recommended Actions:

  • Log every caught error with:

    • Widget identity (name, type, state)
    • User/app session details
    • Stack trace
    • Device/environment info
  • Use structured error reporting:

    onError: (details) {
    // Example with Sentry
    Sentry.captureException(
    details.exception,
    stackTrace: details.stack,
    withScope: (scope) {
    scope.setExtra('widget', context.widget.runtimeType.toString());
    },
    );
    }
  • Analyze error volume and affected users to prioritize fixes.

  • Consider exposing a feedback option in the fallback UI for beta or QA builds:

    fallbackBuilder: (details) => Column(
    children: [
    Text('A problem occurred.'),
    ElevatedButton(
    onPressed: () => launchReportFlow(details),
    child: Text('Send Feedback'),
    ),
    ],
    )

5. Ensuring Reliability at Scale​

To make your error boundary pattern robust:

  • Test with QA:

    • Simulate specific failures using test harnesses or by injecting faults.
    • Validate fallback UI across devices and OS versions for consistent UX.
  • Implement Continuous Monitoring:

    • Set up dashboards for error rates, trends, and regression analysis.
    • Push fixes quickly for high-impact failures.
  • Automate Recovery where Possible:

    • Allow users to retry failed widgets (re-initialize or reload).
    • Use progressive enhancements to render partial UI where possible, instead of full blank/error states.
  • Fail Fast, But Recover Gracefully:

    • Surface recoverable errors to users, but never let a single widget failure bring down your app.

Conclusion: Shipping User-Trustworthy Flutter Apps​

By implementing custom error boundaries, Flutter teams can close real-world reliability gaps: catching widget-level errors, presenting resilient fallback UIs, capturing rich debugging signals, and driving observability at depth. Performance tuning and error context are not optional-without these, even the best error boundary is just a band-aid.

Empower your engineering and QA teams to spot, debug, and fix flaky UI before users ever notice. Start small-wrap a few high-risk widgets, integrate observability, and iterate. Over time, robust error boundaries will become a cornerstone of your app’s reputation and reliability.


Key Takeaways:

  • Custom error boundaries make your Flutter UI bulletproof against unexpected failures.
  • Scoped error catching preserves app usability and debuggability.
  • Observability and actionable reporting turn silent failures into resolved incidents.
  • Performance profiling and targeted wrapping maintain smooth UX.

Forward-looking: Stay tuned for advanced patterns-like async error boundaries for FutureBuilders and platform channel error handling, taking your engineering practice to the next level.


Happy building-may your UIs be as resilient as your ambition!