Bug Handler
A resilient, privacy‑first error reporting toolkit for Dart & Flutter applications.
It gives you:
- A central client to create, sanitize, deduplicate, rate‑limit, and send error reports.
- Built‑in context providers (app, device, network, UI, user) with caching and opt‑in heavy data.
- A flexible sanitization pipeline (masking by key and content, regex rewrites, depth/size pruning, allow/deny filters).
- Policy controls (severity gating, environment allow‑list, sampling, rate‑limit, dedupe window).
- Outbox persistence for offline scenarios and delivery retries.
- A composable reporter pipeline (console logging, share sheet; adapters stubs for Sentry/Crashlytics).
- Developer‑friendly guard helpers, a Result type, and a Flutter ErrorBoundary widget.
- A typed exception hierarchy that standardizes error shape and severity across domains.
Import
package:bug_handler/bug_handler.dartfor the reporting APIs. Flutter bindings, the error boundary and HTTP status helpers have separate imports.
AI coding-assistant support (agent plugin)
Package-specific support for Claude Code and OpenAI Codex is available as an installable agent plugin, maintained in this repository. This is developer tooling for coding agents - it is not a runtime feature of the Dart package, and it is not part of the pub.dev archive; it installs from this Git repository.
Supported surfaces: Claude Code (CLI, desktop, and other Claude Code surfaces that support plugins); Codex CLI v0.131.0+ and ChatGPT Work mode (Codex plugins are currently not available in the IDE extension, Chat mode, or mobile).
Claude Code
/plugin marketplace add omar-hanafy/bug_handler
/plugin install bug-handler@bug-handler
OpenAI Codex
codex plugin marketplace add omar-hanafy/bug_handler
codex plugin add bug-handler@bug-handler
Start a new session after installing (required by Codex; in Claude Code run /reload-plugins or restart).
The plugin covers setup, guards, custom reporters, privacy, diagnosis and code review. For upgrades, use migrate-legacy-api for 0.0.1-dev.x or migrate-dev6-to-dev7 for 1.0.0-dev.6.
Example prompts:
- "Wire bug_handler into this app - we already initialize Sentry in bootstrap."
- "Why do errors from staging never arrive in our backend?"
- "Migrate this project off the old BugReporter API."
The plugin contains instructions, reference material and illustrative fixtures. The current guidance covers dev.7, with migrations for older versions. Installation and troubleshooting.
Table of contents
Installation
Version 1.0.0-dev.7 requires Flutter 3.38.1 or later. Add it to your app’s pubspec.yaml.
dependencies:
bug_handler: ^1.0.0-dev.7
Import the main library in your app.
import 'package:bug_handler/bug_handler.dart';
Upgrading from dev.6. Native reporters and provider plugin injections keep
their existing APIs. For a shared browser/native reporter, replace a file used
for upload with the attachment reporter. For browser tests with
injected plugins, switch to provider readers. Browser share
tests that intercepted SharePlatform.instance should now exercise Web Share
or the download. Check exception equality if your app
uses exceptions as state values or map keys.
Quick start
Initialize once during app bootstrap and run your app under the provided bindings:
import 'package:bug_handler/bug_handler.dart';
import 'package:bug_handler/flutter/bindings.dart';
import 'package:flutter/foundation.dart' show kReleaseMode;
import 'app.dart' show MyApp;
Future<void> main() async {
await BugReportBindings.runAppWithReporting(
app: () => const MyApp(),
config: ClientConfig(
environment: kReleaseMode ? 'prod' : 'dev',
baseProviders: [AppContextProvider()],
sanitizers: [
DefaultSanitizer(),
MaxDepthSanitizer(maxDepth: 8),
TruncatingSanitizer(maxString: 2_000, maxList: 200, maxMapEntries: 200),
SizeBudgetSanitizer(maxBytes: 60 * 1024), // ~60 KB cap
],
policy: Policy(
minSeverity: Severity.error,
reportHandled: true,
environments: {'prod', 'staging', 'dev'},
sampling: 1.0,
rateLimit: RateLimit(20, Duration(minutes: 1)),
dedupe: DedupeStrategy.windowed(Duration(seconds: 30)),
),
reporters: const [ConsoleReporter()],
maxBreadcrumbs: 100,
),
);
}
Capture and report an exception anywhere:
await BugReportClient.instance.capture(
DataProcessingException(
userMessage: 'Could not load profile.',
devMessage: 'Failed to parse UserDto from /me',
data: responseBody,
operation: 'parsing',
),
);
Add runtime user context (masking is handled by your sanitizers):
BugReportClient.instance.addContextProvider(
UserContextProvider(
id: currentUser.id,
email: currentUser.email,
role: currentUser.role,
manualOnly: true, // only in user-initiated reports
),
);
Core concepts
BugReportClient
The central orchestrator (core/client.dart):
- Singleton:
BugReportClient.instance. initialize(ClientConfig)builds the reporter pipeline.- Collects base + additional + runtime context providers, optionally including manual‑only providers for user‑initiated reports.
- Computes fingerprints (type, optional
metadata.source, top stack frame, hashed dev message) used for dedupe/grouping. - Applies transforms, then sanitizers, producing a sanitized payload.
- Enforces policy: severity gating, environment allow‑list, sampling, dedupe window, and a rate limiter.
- On send failure or rate‑limit, persists to Outbox for later flush.
Key methods:
Future<void> initialize(ClientConfig config);
void addContextProvider(ContextProvider p);
void removeContextProvider(ContextProvider p);
void clearContextProviders();
void addBreadcrumb(String message, { Map<String, dynamic> data = const {}, DateTime? timestamp });
void clearBreadcrumbs();
Future<ReportEvent> createEvent(BaseException e, { Map<String, dynamic> additionalContext = const {}, bool manual = false, bool handled = true });
Future<bool> report(ReportEvent e);
Future<ReportEvent> capture(BaseException e, { ... }); // create + report
Future<void> flush(); // send any Outbox items via current pipeline
ClientConfig & Policy
Defined in core/config.dart.
class ClientConfig {
final String environment; // e.g., "dev", "staging", "prod"
final List<ContextProvider> baseProviders;
final List<ContextProvider> additionalProviders;
final List<Sanitizer> sanitizers;
final List<EventTransform> transforms; // ReportEvent -> ReportEvent
final Policy policy;
final List<Reporter> reporters;
final int maxBreadcrumbs;
}
Policy controls pre‑send gating:
minSeverity: drop events less severe than threshold.reportHandled: include caught errors, not only crashes.environments: required environment allow‑list (empty = all).samplingcontrols the fraction of eligible events kept for delivery. The default is1.0.rateLimit:RateLimit(maxEvents, perWindow).dedupe:DedupeStrategy.windowed(window); drop repeated fingerprints within window.
ReportEvent
Canonical, serializable event (core/event.dart):
- Immutable with JSON serializer (
toJson) andfromJson. - Contains
exception(typed),context,breadcrumbs,fingerprints,attachments,handledandtimestamp. BugReportClient.createEventandcaptureapply your configured sanitizers. A directly constructed event serializes its fields as supplied.report(event)uses the prepared event and does not run sanitizers again.- Reporters should read
toMap()ortoJson()for every value they output. The typedexceptionandcontexton a newly captured event still hold the values from before sanitization.
final event = await BugReportClient.instance.createEvent(e);
final json = event.toJson();
Context providers
Base contract in context/provider.dart:
ContextProvideris immutable and returns aFutureOr<Map<String, dynamic>> getData().manualReportOnlylets you include heavy or sensitive data only for user‑initiated reports.CachedContextProvidershares in-flight reads and caches successful results for its TTL. CallclearCache()to force the next read to collect fresh data, even while an older read is finishing.
Built‑ins:
-
AppContextProvider (
built_in/app.dart)- Package metadata:
appName,packageName,version,buildNumber,buildSignature,installerStore. - Lightweight signals: network
interfaces(fromconnectivity_plus), batterylevel(frombattery_plus,-1when the read throws). On web the plugin returns0if the browser battery API is unavailable. - Cache: 2 minutes. Supports
additional()hook. The web default looks up the app'sversion.jsonthrough the registered package-info plugin. If your app already loaded package metadata from a custom CDN or seeded the plugin's mock cache, pass it throughAppContextProvider.withReaders(readPackage: …). See the dev.6 migration example.
- Package metadata:
-
DeviceContextProvider (
built_in/device.dart)- Platform‑specific device info via
device_info_plus. - Device fields can include a host name, user name or stable device identifier, depending on the platform. Use a filter to remove fields you don't want to report.
- Cache: 1 hour. On error, minimal
{ platform: ... }fallback.
- Platform‑specific device info via
-
NetworkContextProvider (
built_in/network.dart)- Normalized active
interfacesviaconnectivity_plus. The browser plugin maps the online flag towifiand the offline flag tonone. It cannot identify the actual network transport. - On native Wi‑Fi, attempts to collect SSID, BSSID and IP addresses when the platform permits it. The default browser provider reports interfaces and omits these Wi‑Fi details. Remove
context.network.wifiwith a deny-list filter if those fields are unsuitable for delivery. - Cache: 1 minute.
- Normalized active
-
UIContextProvider (
built_in/ui.dart)- manualReportOnly = true.
- Captures theme, color scheme, text theme sizes, platform, MediaQuery metrics (size, DPR, padding/insets, text scaling, orientation), locale, text direction, Navigator state and scheduler timing. Requires a
BuildContext.
-
UserContextProvider (
built_in/user.dart)- Lightweight user/session data:
id,email,role,tenantId, plus arbitrarytraits. - Opt‑in
manualOnlyflag to include only on user‑initiated reports.
- Lightweight user/session data:
Add your own provider:
class CartContextProvider extends ContextProvider with CachedContextProvider {
@override
String get name => 'cart';
@override
Duration get cacheDuration => const Duration(seconds: 30);
@override
Future<Map<String, dynamic>> collect() async {
// never throw; return {} on failure
return {
'items': cart.items.length,
'total': cart.total,
};
}
}
Register it via config or at runtime with BugReportClient.instance.addContextProvider(...).
Sanitizers & Filters
Defined in privacy/sanitizers.dart and privacy/filters.dart.
Configure sanitizers explicitly. The default ClientConfig.sanitizers list is empty. The client runs them in order before storing or delivering an event.
-
DefaultSanitizer matches built-in and custom sensitive keys across case, spaces, dashes and underscores. For example,
accessTokenandaccess_tokenmatch the same rule. The default field mask fully hides values of up to three characters. Content checks also mask token-like strings and card-like numbers. Report and breadcrumb timestamps generated by the package stay readable. -
RegexValueSanitizer: global value rewrites via regex rules.
-
MaxDepthSanitizer: prunes deep structures with a
<redacted:depth>marker. -
TruncatingSanitizer: caps string length, list length, and map entry count.
-
SizeBudgetSanitizer limits the UTF-8 size of the JSON, marking or removing top-level values as needed. It retains
exception,timestampandfingerprintsas long as the budget allows. The smallest result is{}, which uses two bytes. -
FilterSanitizer wraps a DataFilter (see below) to perform allow/deny operations.
Filters operate on arbitrary nested maps using dotted paths and wildcards:
-
Path syntax examples:
a.b.cexact patha.*.csingle‑level wildcarda.**.cmatch any depth fromatoc**.tokenany key namedtokenanywhere
AllowListFilter keeps the selected fields together on each matching list element. DenyListFilter removes matching paths. For example, context.network.** removes the whole network subtree. Empty paths are ignored.
Example configuration:
final allow = FilterSanitizer(
AllowListFilter({
'exception', // keep entire exception section
'timestamp',
'context.app', // whole app context
'context.device.model', // only device.model
'breadcrumbs', // breadcrumbs list
}),
);
final deny = FilterSanitizer(
DenyListFilter({
'**.token', // drop any token
'context.user.email', // drop user email
'context.network.wifi', // drop wifi details if you don’t need them
}),
);
final config = ClientConfig(
// ...
sanitizers: [
DefaultSanitizer(),
deny,
allow,
MaxDepthSanitizer(maxDepth: 8),
TruncatingSanitizer(maxString: 2000),
SizeBudgetSanitizer(maxBytes: 60 * 1024),
],
);
Use
captureSafelywhen a custom sanitizer or storage failure must leave the calling code free to continue.captureexposes those errors to its caller.
Reporters
Base contract in reporters/reporter.dart:
abstract class Reporter {
const Reporter();
Future<bool> send(ReportEvent event); // required
Future<bool> share(ReportEvent event) async => false; // optional
@protected String defaultFileName(ReportEvent event);
}
For an upload that accepts bytes, build a ReportAttachment on any target.
It snapshots the retained payload as UTF-8 JSON and supplies its media type
and a sanitized file name. Each read of bytes gives the caller a fresh
Uint8List. Pass your own file name if the receiver requires one.
class AttachmentReporter extends Reporter {
const AttachmentReporter(this.upload);
final Future<bool> Function(ReportAttachment attachment) upload;
@override
Future<bool> send(ReportEvent event) async {
try {
return await upload(ReportAttachment.fromEvent(event));
} catch (_) {
return false;
}
}
}
The upload callback can pass attachment.bytes, attachment.mimeType and
attachment.name to a multipart client. A native reporter that needs a real
file can still call await generateFile(event, directory: directory) from
its subclass. Keep that reporter and its dart:io import in native code.
Built‑ins:
-
CompositeReporter (
reporters/composite_reporter.dart) Fans out to multiple reporters. A send is considered successful if any reporter succeeds. Swallows individual failures to keep the pipeline resilient. -
ConsoleReporter (
reporters/console_reporter.dart) Logs a compact summary of the serialized payload, including only retained message and stack fields. Options:enabled,prettyJson(log full payload),maxContextKeysPreview,maxMessageLength. -
ShareReporter (
reporters/share_reporter.dart) Native targets use the registeredshare_plusimplementation. Browsers offer the JSON file through Web Share when file sharing is available and start a download otherwise. The default subject, body and attachment use the serialized payload. Native sharing adds a unique suffix to the default file name on each handoff. UsefileNameBuilderfor a specific name. CustomtextBuilderandfileNameBuildercallbacks receive the event and should readevent.toMap(). InClientConfig.reporters,send()invokes sharing for automatic reports and retries too. For an explicit share button, create a manual event and pass it toshare()directly.final event = await BugReportClient.instance.createEvent(error, manual: true); final handedOff = await const ShareReporter().share(event);A dismissal or failed share returns
false. Starting a browser download or handing the attachment to a platform that provides no completion feedback returnstrue. Calling a reporter directly bypasses the client’s delivery policy.
Adapters (stubs provided; implement in your app layer):
reporters/adapters/sentry.dart— implement aReporterthat convertsReportEventto Sentry payloads.reporters/adapters/crashlytics.dart— implement aReporterthat forwards to Crashlytics.
Example custom reporter:
class MyApiReporter extends Reporter {
const MyApiReporter(this.client);
final MyApiClient client;
@override
Future<bool> send(ReportEvent event) async {
try {
final ok = await client.postJson('/errors', event.toMap());
return ok;
} catch (_) {
return false;
}
}
}
Outbox
The client queues an event when the rate limit is reached or every reporter fails. Native apps store the serialized payload under bug_report_outbox in the app’s documents directory. Web apps use the origin’s localStorage, so the queue survives a reload while that site data is retained.
flush() sends the saved payload to the current reporters. Filters may remove or rewrite the event ID, timestamp or exception without preventing replay. A successful send acknowledges the original queue entry. Failed deliveries stay pending. Generated IDs distinguish captures within the same clock tick. Treat them as opaque if you use them as backend keys.
You can trigger flush at strategic times (e.g., app resume, connectivity available):
await BugReportClient.instance.flush();
Breadcrumbs
A ring buffer of recent diagnostic notes:
BugReportClient.instance.addBreadcrumb(
'tapped_submit',
data: {'screen': 'checkout', 'step': 2},
);
- Configurable size via
ClientConfig.maxBreadcrumbs(default 100). - Breadcrumbs are attached to every event created after recording them.
- Use
clearBreadcrumbs()to reset between flows if helpful.
Flutter wiring
Global bindings
flutter/bindings.dart wires crash‑like sources:
FlutterError.onError(build/layout/paint errors).ui.PlatformDispatcher.onError(unhandled errors crossing framework boundaries).- A guarded zone for uncaught async errors when the helper initializes Flutter.
- An error listener for the current isolate on native platforms.
Use:
import 'package:bug_handler/flutter/bindings.dart';
await BugReportBindings.runAppWithReporting(
app: () => const MyApp(),
config: myConfig,
captureFrameworkErrors: true,
capturePlatformDispatcherErrors: true,
attachIsolateErrorListener: true,
useDefaultFlutterErrorPresentation: true,
);
Call the helper before WidgetsFlutterBinding.ensureInitialized() to run Flutter initialization and your app in the same guarded zone. If startup code already initialized Flutter, call the helper from that same zone. In that case the helper preserves your zone, and its existing error handling determines coverage of uncaught async errors. Framework and platform-dispatcher handlers still run when enabled. On web the helper skips the isolate listener.
Framework errors reach the client as FlutterErrorException with handled: false.
ErrorBoundary widget
A pragmatic, local error boundary that shows a fallback UI when operations in its subtree fail and are reported through the boundary.
import 'package:bug_handler/bug_handler.dart';
import 'package:bug_handler/flutter/error_boundary.dart';
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
return ErrorBoundary(
onRetry: () => context.read<ProfileCubit>().refresh(),
showDetails: !kReleaseMode,
child: const _ProfileContent(),
);
}
}
class _ProfileContent extends StatelessWidget {
const _ProfileContent();
@override
Widget build(BuildContext context) {
final boundary = ErrorBoundary.of(context);
return ElevatedButton(
onPressed: () async {
try {
await boundary.guardFuture(
() => context.read<ProfileCubit>().load(),
source: 'ProfileScreen.load',
);
} on BaseException {
// The boundary captured the failure and shows the fallback.
}
},
child: const Text('Load profile'),
);
}
}
Helpers on ErrorBoundaryState:
- The guards display the fallback and capture failures automatically, excluding manual-only providers. Their normalized errors still reach the caller. A guarded stream forwards the normalized error with its source stack trace before later data or completion.
show(BaseException)— manually display an error in this boundary.- The fallback’s Report button captures the displayed error again with
manual: true. It collects manual-only providers and sends through the configured reporters under normal policy. Dedupe can suppress a recent automatic report of the same type. Retry clears the fallback and callsonRetry.
Guard helpers & Result
For non‑UI logic, core/guard.dart provides guard functions and a small Result ADT (core/result.dart) for ergonomic flows.
final res = await guard<User>(() async {
return api.fetchCurrentUser();
}, source: 'ProfileRepository.fetchCurrentUser');
res.match(
ok: (user) => emit(ProfileLoaded(user)),
err: (e) => emit(ProfileError(e.userMessage)),
);
// or chain:
final fullName = res.map((u) => '${u.first} ${u.last}').unwrapOr('Guest');
-
guard<T>runs the action, returnsOk(value)on success. On error, it normalizes to aBaseException, reports automatically, and returnsErr(e). -
guardSync<T>does the same synchronously and reports in a fire‑and‑forget task so you don’t block the UI. -
parser<T>(build, data: raw)wraps JSON/model construction and throws a typedParsingExceptionwhen it fails. -
normalizeError(error, stack, source: '...')maps:- already
BaseException→ passthrough - Flutter
PlatformException→PlatformOperationException.fromPlatformException FormatException→ParsingException- otherwise →
UnexpectedException
- already
Include a source string to improve grouping via fingerprints.
Exceptions overview
All exceptions extend BaseException (exceptions/base_exception.dart) which is immutable, equatable, severity‑aware, and carries userMessage, devMessage, optional cause, optional stack, and immutable metadata.
Version 1.0.0-dev.7 accepts Equatable 2.x and 3.x. With Equatable 3, values of different runtime types can compare equal inside exception metadata or custom props when their == agrees. If your app relies on the type distinction, keep equatable: ^2.0.8 or include a type discriminator in the compared values.
Key types:
-
ApiException Wraps HTTP failures and enriches metadata via
HttpStatusCodeInfo(helpers.dart), which provides normalized flags likeisAuthenticationError,isRateLimitError,isServerError, derived user/dev messages, and severity mapping.final info = HttpStatusCodeInfo(429); throw ApiException( httpStatusInfo: info, endpoint: '/v1/items', method: 'GET', responseBody: body, ); -
AuthException and TokenException Authentication and session lifecycle problems (TokenException uses severity=error by default).
-
DataProcessingException and ParsingException For IO/transform/mapping;
ParsingExceptionautomatically includes target type and raw payload. -
FlutterErrorException Wraps
FlutterErrorDetailsfrom framework crashes; used by the global bindings. -
InitializationException and ComponentNotInitializedException For bootstrap/setup failures. Initialization is
Severity.critical. -
NavigationException, RouteNotFoundException, InvalidRouteArgumentsException UI routing issues. Defaults to
Severity.warningandisReportable=false. -
PermissionException Normalized permission errors with
PermissionStatusand appropriate user messages and severities. -
PlatformOperationException and MediaException Platform channel/OS failures; conveniences for media flows (upload, download, picker, processing, permission, format, size). Factory
PlatformOperationException.fromPlatformException(...)maps Flutter’sPlatformExceptionto user/dev messages and severity. -
StorageException, CacheException, SecureStorageException Storage/caching failures with operation/key context.
-
ValidationException Input/constraint violations;
Severity.warning,isReportable=falseby default. -
UnexpectedException Catch‑all fallback used during normalization and global handlers.
Transform hooks
Before sanitization, you can transform events:
ReportEvent tagSource(ReportEvent e) {
final src = e.exception.metadata['source'] ?? 'unknown';
final ctx = Map<String, dynamic>.from(e.context)
..putIfAbsent('tags', () => <String, dynamic>{})['source'] = src;
return e.copyWith(context: ctx);
}
final config = ClientConfig(
// ...
transforms: [tagSource],
);
Use transforms to:
- Add/normalize tags.
- Rewrite dev messages for consistent grouping.
- Attach routing/screen info from your app state.
Extending
Custom context providers
Implement ContextProvider (optionally with CachedContextProvider) and add via config or at runtime.
Custom reporters
Implement Reporter.send using event.toMap(), event.toJson() or a JSON attachment. See the attachment reporter example.
Custom sanitizers/filters
Compose SanitizerChain. Wrap AllowListFilter/DenyListFilter via FilterSanitizer to tailor payload shape to your privacy posture.
Testing & tips
-
Prefer
ConsoleReporterin dev/test. SetprettyJson: truewhen you need full payload dumps. -
For tests that run in a browser and on the VM, supply the readings each provider needs. Other readings keep their platform defaults.
final app = AppContextProvider.withReaders(readBatteryLevel: () => 75); final device = DeviceContextProvider.withReader(() => {'platform': 'test'}); final network = NetworkContextProvider.withReaders( readInterfaces: () => ['wifi'], readWifi: () => (ssid: 'Guest', bssid: null, ipv4: null, ipv6: null), );Native tests can keep using the dev.6 plugin arguments, including
AppContextProvider(packageInfo: fakePackage, battery: fakeBattery),DeviceContextProvider(deviceInfo: fakeDevice)andNetworkContextProvider(connectivity: fakeConnectivity, info: fakeNetwork). -
Use
UserContextProvider(manualOnly: true)to avoid collecting PII automatically. -
Use a stable
sourcelabel to identify where a failure occurred. The client’s default dedupe groups by exception type. -
If you rely on Outbox, call
flush()on app resume or when connectivity returns.
Troubleshooting
-
Nothing gets sent Check
Policygates:- Is your event severity below
minSeverity? - Is
reportHandledfalse while your exception was handled? - Is the current
environmentinPolicy.environments? - Is
sampling< 1.0? - Are you hitting
rateLimitordedupewindows?
- Is your event severity below
-
Payload is missing fields A sanitizer or allow list filter may be removing them. Review your
sanitizersorder and filter paths. -
Wi‑Fi fields are null Platform permissions or plugin support may prevent access;
NetworkContextProvidergracefully omits them. -
Battery level is ‑1 That’s the fallback when a platform doesn’t support battery queries.
-
Queued reports accumulate Ensure you include at least one reporter that can succeed in your runtime environment, and call
flush()at appropriate times. -
“Report” button does nothing Check the configured reporters and policy, especially the dedupe window after a guarded failure. If the button should open a share sheet for each tap, use a custom
fallbackBuilderand the explicit sharing example above.
FAQ
Q: What’s considered “manual” reporting?
A: Set manual: true in createEvent/capture or use the ErrorBoundary’s “Report” action. Manual mode includes manualReportOnly providers (like UIContextProvider and any of your own manual‑only providers).
Q: How are duplicates detected? A: The client uses the first fingerprint, normally the exception type. Two failures of the same type can deduplicate within the configured window even when their messages, sources or stacks differ.
Which capture method should I use inside an error handler?
captureSafely contains failures from reporting and skips capture before initialization. Use capture when you need the created event or want to handle a sanitizer or outbox failure. For a delivery result, pass a created event to report and check its boolean return value.
Q: How is HTTP severity determined in ApiException?
A: HttpStatusCodeInfo maps status codes to severity: 5xx → error, 401/403 → warning, 404 → info, 429 → warning, otherwise error. It also provides user/dev messages and retry hints you can use in your UX.
Q: Can I attach binary attachments (screenshots, logs)?
A: ReportEvent.attachments exists in the model. Implement a custom reporter that uploads attachments and reference them in your payload.
File map (what’s in this package)
bug_handler.dart— core reporting types, providers, exceptions, sanitizers and reporters.- Context
context/provider.dart,context/built_in/{app,device,network,ui,user}.dart - Core
core/{client,config,event,guard,outbox,result}.dart - Exceptions
exceptions/*.dart(API/Auth/Data/FlutterError/Initialization/Navigation/Permission/Platform/PlatformPayment/Storage/Unexpected/Validation) - Flutter integration
flutter/{bindings,error_boundary}.dart - Privacy
privacy/{filters,sanitizers}.dart - Reporters
reporters/{reporter,composite_reporter,console_reporter,share_reporter}.dartreporters/adapters/{sentry,crashlytics}.dart(stubs) - Utilities
helpers.dart(HTTP status helpers, sensitive fields utilities)
License
BSD 3-Clause License - see LICENSE.
Appendix: Practical configuration recipes
Minimal dev setup
ClientConfig(
environment: 'dev',
baseProviders: [AppContextProvider(), DeviceContextProvider()],
additionalProviders: [NetworkContextProvider()],
sanitizers: [DefaultSanitizer()],
reporters: [ConsoleReporter(prettyJson: true)],
)
Production with Wi-Fi details and email fields excluded
ClientConfig(
environment: 'prod',
baseProviders: [AppContextProvider(), DeviceContextProvider()],
additionalProviders: [
NetworkContextProvider(),
UserContextProvider(id: userId, manualOnly: true),
],
sanitizers: [
DefaultSanitizer(),
FilterSanitizer(DenyListFilter({'context.network.wifi', '**.email'})),
MaxDepthSanitizer(maxDepth: 6),
TruncatingSanitizer(maxString: 1000, maxList: 100, maxMapEntries: 150),
SizeBudgetSanitizer(maxBytes: 48 * 1024),
],
policy: Policy(
minSeverity: Severity.error,
reportHandled: true,
environments: {'prod'},
sampling: 1.0,
rateLimit: RateLimit(10, Duration(minutes: 1)),
dedupe: DedupeStrategy.windowed(Duration(seconds: 60)),
),
reporters: [MyApiReporter(apiClient)],
)
Using guards with source labels
final res = await guard(() => repo.saveOrder(order),
source: 'Checkout.saveOrder',
onSuccess: (_) => BugReportClient.instance.addBreadcrumb('order_saved'),
onError: (e) => BugReportClient.instance.addBreadcrumb('order_save_failed', data: {'code': e.runtimeType}),
);
Libraries
- bug_handler
- context/built_in/app
- context/built_in/device
- context/built_in/network
- context/built_in/ui
- context/built_in/user
- context/provider
- core/client
- core/config
- core/event
- core/guard
- core/outbox
- core/result
- exceptions/api_exception
- exceptions/auth_exception
- exceptions/base_exception
- exceptions/data_exception
- exceptions/flutter_error_exception
- exceptions/initialization_exception
- exceptions/permission_exception
- exceptions/platform_exception
- exceptions/platform_payment_exception
- exceptions/storage_exception
- exceptions/unexpected_exception
- exceptions/validation_exception
- flutter/bindings
- flutter/error_boundary
- helpers
- privacy/filters
- privacy/sanitizers
- reporters/adapters/crashlytics
- reporters/adapters/sentry
- reporters/composite_reporter
- reporters/console_reporter
- reporters/report_attachment
- reporters/reporter