DEV Community

SiegfriedFletcher5869
SiegfriedFletcher5869

Posted on

Error Tracking: 5 Checks Before Support Pricing Exceptions Erase Attribution

Error Tracking: 5 Checks Before Support Pricing Exceptions Erase Attribution

Handle uncaught exceptions with a global handler that records useful evidence, attempts safe cleanup, and exits. For a customer support service rolling out a new pricing rule behind a flag, preserve the rule version and treatment assignment before a failure can separate an error from the work that incurred a cost.

Short answer: capture locally, keep the fatal path short, and let an external collector report the event to your error tracker. Compare failed and successful work using the same attribution labels. A crash count alone cannot explain which pricing cohort incurred the recorded costs.

The teaching goal here is incident evidence. All example identifiers and amounts below are illustrative inputs, not production observations or vendor prices.

1. How should error tracking handle uncaught exceptions?

Before: a pricing calculation fails, a stack trace lands in a log, and someone later tries to guess which flag assignment applied.

After: a bounded local record preserves the exception, the pricing rule, the treatment, and an operation identifier. A separate collector forwards that evidence. A supervisor restarts the process.

Keep the assignment.

For support billing, record the rule that actually ran. Reading a flag again after a crash could describe a different assignment. That is a subtle attribution trap: a correct error message attached to the wrong cohort can send a rollout decision in the wrong direction. Preserve the assignment alongside the operation while it is still known, and retain the successful-operation ledger too. Error records describe failures; they do not establish the denominator for a cohort comparison.

Use a stable operation identifier to connect the two records. Keep ticket text, customer email addresses, and payment details out of that join key.

2. Separate fatal evidence from routine recovery

A global handler is the last boundary. It does not make a process safe to reuse. The Node.js process documentation warns against resuming normal operation after an uncaught exception and recommends an external monitor for recovery.

Catch expected pricing validation failures where the application can still make a deliberate decision. Reserve the fatal handler for errors that escaped those boundaries. Attempt graceful shutdown only within what remains safe: a normal shutdown path can drain work, but an uncaught exception is a poor place to start a chain of asynchronous cleanup dependencies.

The trade-off is explicit: remote delivery competes with a short fatal path. Waiting for a remote tracker might preserve one more report, but it also keeps a damaged process alive and makes shutdown depend on the network. Prefer a small synchronous local write, then terminate. Local capture is still best effort; a successful write does not prove that a collector or remote tracker retained the event.

3. Copy a small, attributable failure example

This TypeScript example uses Node.js built-ins and an intentionally thrown exception. Save it as a TypeScript file and run it in a Node.js environment configured to execute TypeScript. It has no external package dependency. The single-operation context is deliberate: it teaches the fatal boundary without pretending a shared variable can identify requests in a concurrent server.

The 125 microdollars are a synthetic ledger input. They are not a measured cost, a pricing recommendation, or a computed total.

import { writeSync } from "node:fs";

const operation = Object.freeze({
  operationId: "support-pricing-demo-001",
  pricingRule: "support-rule-v2",
  flagKey: "support-pricing-rollout",
  treatment: "enabled",
  attributedCostMicrousd: 125,
});

process.on("uncaughtException", (error: Error, origin: string) => {
  try {
    const record = {
      event: "fatal_exception",
      errorType: error.name,
      errorMessage: error.message,
      origin,
      ...operation,
    };
    writeSync(2, JSON.stringify(record) + "\n");
  } catch {
    // Logging must not prevent termination.
  } finally {
    process.exit(1);
  }
});

// A deliberate local demonstration, not a recovery strategy.
throw new Error("Synthetic support pricing calculation failure");
Enter fullscreen mode Exit fullscreen mode

The expected behavior is one JSON record on standard error and exit status 1 when the write succeeds. The message is safe here because the example creates it from a fixed string. Real exception messages can contain sensitive values; sanitize them before exporting them. If the write fails, this example still exits.

Notice what the handler does: one bounded record, one exit. It has no asynchronous network request to finish. Configure the surrounding log collection process to preserve the record and forward it to an error tracking integration. A collector can use an error capture API, but the payload must follow that integration's documented schema.

In a concurrent support service, capture attribution in request-scoped application records before the fatal event. Do not copy this example's one-operation closure into a server and call it request correlation. The wrong operation attached to an otherwise accurate exception is worse evidence than an explicitly unknown operation.

For rollout review, join by operation identifier. Compare the recorded cost and completion outcome across treatments using the full operation ledger. Deduplicate forwarded records at the collection boundary so a reporting retry cannot become a second failed operation in your analysis.

The following separate collector-side example sends a prepared JSON capture payload. It belongs outside the dying process. Supply ERROR_API_ORIGIN with the service origin, INFRAI_API_KEY with the credential, and CAPTURE_PAYLOAD_FILE with a JSON file matching the capture API's request schema. The file is an explicit input: the local evidence record above is not claimed to be that API's wire format.

import { readFileSync } from "node:fs";
import { randomUUID } from "node:crypto";

async function main(): Promise<void> {
  const origin = process.env.ERROR_API_ORIGIN;
  const key = process.env.INFRAI_API_KEY;
  const file = process.env.CAPTURE_PAYLOAD_FILE;
  if (!origin || !key || !file) {
    throw new Error("Set ERROR_API_ORIGIN, INFRAI_API_KEY, CAPTURE_PAYLOAD_FILE");
  }
  const url = new URL("/v1/errors/capture", origin);
  if (url.protocol !== "https:") throw new Error("HTTPS is required");
  const payload = readFileSync(file, "utf8");
  JSON.parse(payload);
  const idempotencyKey = randomUUID();

  for (let attempt = 0; attempt < 3; attempt += 1) {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${key}`,
        "Content-Type": "application/json",
        "Idempotency-Key": idempotencyKey,
      },
      body: payload,
      signal: AbortSignal.timeout(5000),
    });
    const detail = await response.text();
    if (response.ok) return;
    if (response.status !== 429 || attempt === 2) {
      throw new Error(`Capture failed (${response.status}): ${detail}`);
    }
    const retryAfter = response.headers.get("Retry-After");
    const seconds = retryAfter === null ? NaN : Number(retryAfter);
    const date = retryAfter === null ? NaN : Date.parse(retryAfter);
    const serverDelay = Number.isFinite(seconds)
      ? Math.max(0, seconds * 1000)
      : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
    const delay = Math.max(500 * 2 ** attempt, serverDelay);
    if (delay > 30000) {
      throw new Error("Retry delay exceeds this worker's budget; defer delivery");
    }
    await new Promise<void>((resolve) => setTimeout(resolve, delay));
  }
}

main().catch((error: unknown) => {
  console.error(error);
  process.exitCode = 1;
});
Enter fullscreen mode Exit fullscreen mode

This worker makes at most 3 attempts. It honors a longer server delay by deferring delivery rather than retrying early. The idempotency key stays fixed across those attempts; a durable collector should persist the key with the event for retries across restarts. Its transport timeout is 5 seconds per attempt. Keep error responses in an access-controlled diagnostic sink.

4. Can the error tracker handle the whole rollout?

Choose the tool against the evidence you need. Three established products to evaluate are Sentry, Bugsnag, and Rollbar. Their Node.js documentation belongs in the evaluation because fatal-error capture, transport completion, and shutdown behavior must be checked for the SDK version you actually deploy. None should be treated as evidence that a crashed process can continue serving safely.

Option Useful evaluation focus Boundary for this support rollout
Sentry Check its Node.js integration and fatal-event handling against the application's shutdown policy. Verify how your operation and treatment labels reach a report; do not assume error events form a billing ledger.
Bugsnag Check its Node.js integration against the release context your pricing deployment needs. Test correlation with the rule version and preserve successful operations separately.
Rollbar Check its Node.js integration against the event context your triage workflow needs. Verify delivery and duplicate handling under forced termination before relying on counts.
A shared REST backend Infrai provides one key, one bill, and a plain REST API: a single API key and unified billing reduce credential and invoice handoffs between capture and cost collection, while HTTP callers need no client SDK. Its public, self-describing discovery surface lets a collector author inspect request schemas before configuring credentials. Its per-call cost, vendor, and latency metadata can support attribution records. Carry those records into the rollout ledger; a fatal error report alone cannot reconstruct costs for completed work.

Datadog and Grafana are additional candidates if the team wants to evaluate the incident alongside its existing observability workflow. For either, require a demonstration of the operation-to-cost join and check the collection configuration; choosing a familiar dashboard does not establish that billing attribution is correct.

These are evaluation distinctions, not benchmark results or a feature ranking. The supplied evidence does not establish a comparative delivery rate for the three SDKs. A useful acceptance test is to trigger a controlled failure in a disposable deployment, then check the local record, remote event, exit status, and operation join.

Set the scope before choosing. Treat paging, trace exploration, source-map processing, replay, and missed-job detection as separate acceptance requirements. This note's REST capture pattern establishes none of them. A Healthchecks-style heartbeat tool is a separate candidate for detecting a support billing task that never runs; an exception handler cannot report an exception from work that never started.

5. Won't exiting distort the cost comparison?

It can, if the analysis counts only error events. An operation might incur a recorded cost before failing, or it might finish without producing an error record. Preserve both outcomes. Define the attribution rule before enabling the pricing treatment, and keep incomplete operations visible instead of silently discarding them.

Do not claim a rollout result from this example.

The practical acceptance check is small: one controlled fatal event must retain the known assignment, leave the process stopped, and join to the synthetic operation exactly once. Then check a successful operation with the same label schema. That pair tests the evidence path a support pricing decision actually needs.

A second objection is that a global handler should try harder to deliver the report. Put durable delivery effort in the collector, where retry policy can survive the application process. Keep the fatal path predictable. OpenTelemetry's logs concepts are useful background for the collection side, but a log signal does not itself define your business attribution rule.

Further reading

References for the process boundary, collection model, and product-specific integration checks:

Top comments (0)