Capture server exceptions with their release and environment, then require fresh import results before declaring a marketplace rollback successful. The deciding constraint is rollback safety. A quiet error feed cannot establish that a scheduled importer ran, finished, or produced usable listings.
Short answer: wrap Next.js API routes, route handlers, server actions, and Node.js background jobs with a shared error boundary. Preserve stack traces, allowlist request headers, and attach deployment-owned release and environment values. Evaluate three checks separately: execution failed, completion is overdue, and expected results are missing. An exception store supplies evidence for the first check; a heartbeat monitor and an application-defined result rule cover the others.
This engineering note uses an illustrative inventory import, not a production incident or benchmark. The implementation below captures local events without assuming a vendor payload schema. That keeps the example inspectable while making its operational boundary explicit.
Why can a completed import still need an alert?
Before: an importer throws, an error appears, and someone considers reverting the deployment.
After: each scheduled window has an expected completion, each attempt records useful output, and each exception identifies the release that executed it. The operator can now distinguish a parser failure from a run that completed but accepted nothing. Those situations can demand different recovery actions, especially when reverting application code does not undo inventory writes already committed by an earlier attempt.
Count useful results.
For this example, a useful run accepts at least one listing from a batch known to contain eligible listings. Zero accepted listings warrant attention only when that eligibility condition holds. A supplier may legitimately send an empty batch. A filter may intentionally reject every item. Paging on every zero would erase that distinction and encourage a rollback without evidence that the deployment caused the missing output.
Diagram in words: scheduled window → validate supplier batch → apply idempotent inventory writes → record eligible and accepted counts → signal completion. An exception branches into captured error context. An overdue completion belongs to heartbeat monitoring. Unexpectedly empty output belongs to the application's result rule.
The three checks share a run identifier, but they retain separate meanings. Keep them separate in the support UI, too. A green completion indicator beside zero accepted listings should invite inspection.
How should API routes and server actions capture error context?
Next.js API routes and server actions are entry points, not evidence that an import produced results. Normalize exceptions at those boundaries and carry the same metadata into background jobs. Preserve the original stack rather than constructing a new exception for each wrapper. Keep request IDs outside the message so retry-specific text does not obscure recurring failures during grouping.
Use deployment configuration for release and environment. A caller-supplied release label should not become evidence for reverting production. For request headers, start with an allowlist; copying cookies or authorization into an exception record creates an unnecessary data-retention problem.
The TypeScript example is a complete local demonstration. Save it as import-observation.ts and run it with a TypeScript runner in a Node.js environment that provides Request. Its event fields belong to the application. They are not a service's request schema, and the in-memory array does not provide durable delivery or notifications.
type Boundary = "api-route" | "route-handler" | "server-action" | "background-job";
type Context = {
boundary: Boundary;
release: string;
environment: string;
runId: string;
request?: Request;
};
type CapturedError = {
name: string;
message: string;
stack: string | null;
context: Omit<Context, "request">;
requestHeaders: Record<string, string>;
};
const captured: CapturedError[] = [];
function normalize(thrown: unknown, context: Context): CapturedError {
const error = thrown instanceof Error
? thrown
: new Error("Import failed with a non-Error value");
const { request, ...tags } = context;
const requestId = request?.headers.get("x-request-id");
return {
name: error.name,
message: error.message,
stack: error.stack ?? null,
context: tags,
requestHeaders: requestId
? { "x-request-id": requestId.slice(0, 128) }
: {},
};
}
async function observe<T>(
context: Context,
work: () => Promise<T>,
): Promise<T> {
try {
return await work();
} catch (thrown) {
captured.push(normalize(thrown, context));
throw thrown;
}
}
type ImportResult = { eligible: number; accepted: number };
async function runDemo(): Promise<void> {
const context: Context = {
boundary: "route-handler",
release: "catalog-r42",
environment: "staging",
runId: "supplier-demo-run-17",
request: new Request("https://marketplace.example/import", {
method: "POST",
headers: { "x-request-id": "import-demo-17" },
}),
};
const result = await observe<ImportResult>(context, async () => ({
eligible: 12,
accepted: 0,
}));
console.log({
completed: true,
resultNeedsAttention: result.eligible > 0 && result.accepted === 0,
accepted: result.accepted,
capturedExceptions: captured.length,
});
try {
await observe(context, async () => {
throw new Error("Supplier response could not be parsed");
});
} catch {
console.log(captured[0]);
}
}
void runDemo().catch((error: unknown) => {
console.error(error);
throw error;
});
The first operation finishes with 12 eligible listings and zero accepted results. It captures no exception. The result rule still requires attention. The second operation throws and captures its stack, selected header, release, environment, and run ID. Neither operation writes inventory or sends a network request.
For a server action or background job, pass the corresponding boundary and omit request when there is no request object. An API route or route handler supplies request metadata through the same normalization boundary. The 128-character header limit is a teaching choice, not a service limit or a privacy guarantee; define a policy for any retained identifier.
One trap deserves extra care. A production capture transport can fail independently of the import, so its delivery error must not replace the original exception. Make capture delivery observable through a separate operational signal. Otherwise, the support page may show the failure of the reporter while losing the parser stack that the rollback decision actually needed. The local array avoids that transport concern for demonstration, but it also disappears when the process exits. Replace it with a documented capture integration before using this pattern operationally. Don't treat the array as a delivery guarantee.
The companion example retrieves an existing captured event for a restricted support page. Run it separately in a Node.js TypeScript environment with fetch and Node typings. Set INFRAI_API_KEY, INFRAI_BASE_URL to the deployment's HTTPS API origin, and ERROR_EVENT_ID to an existing event ID. The response stays unknown until the application validates its documented schema. No inventory writes are involved, so retrying this read cannot replay an import.
async function lookupCapturedEvent(): Promise<unknown> {
const key = process.env.INFRAI_API_KEY;
const origin = process.env.INFRAI_BASE_URL;
const eventId = process.env.ERROR_EVENT_ID;
if (!key || !origin || !eventId) {
throw new Error("Set INFRAI_API_KEY, INFRAI_BASE_URL, and ERROR_EVENT_ID");
}
const path = "/v1/errors/get/{event_id}".replace("{event_id}", encodeURIComponent(eventId));
const url = new URL(path, origin);
if (url.protocol !== "https:") throw new Error("Use an HTTPS API origin");
for (let attempt = 0; attempt < 4; attempt++) {
const response = await fetch(url, {
method: "GET",
headers: { Authorization: `Bearer ${key}` },
redirect: "error",
});
const body = await response.text();
if (response.status === 429 && attempt < 3) {
const retryAfter = response.headers.get("retry-after");
const seconds = retryAfter === null ? NaN : Number(retryAfter);
const date = retryAfter === null ? NaN : Date.parse(retryAfter);
const delay = Number.isFinite(seconds)
? Math.max(0, seconds * 1000)
: Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
await new Promise<void>((resolve) => {
setTimeout(resolve, Math.max(delay, 1000 * 2 ** attempt));
});
continue;
}
if (!response.ok) {
throw new Error(`Event lookup returned ${response.status}: ${body}`);
}
return JSON.parse(body) as unknown;
}
throw new Error("Event lookup retry limit reached");
}
void lookupCapturedEvent().then(console.log).catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});
This example permits at most 4 attempts and honors Retry-After alongside exponential backoff. These are example choices, not measured service limits. Keep credentials and diagnostic response bodies on the server; don't return them to public clients.
Compare tools against the missing evidence
An error tracker, a heartbeat monitor, and a result-signal pipeline answer different questions. Compare their roles before comparing dashboards. The important selection criterion here is whether an operator can connect a suspected release to failed execution and then verify useful output after recovery.
| Option | Relevant role | Boundary to evaluate for this importer |
|---|---|---|
| Sentry | Exception grouping and fingerprint mechanics | Compare repeat parser failures as issues; define useful import output separately. |
| Healthchecks | Heartbeat monitoring for scheduled work | Check expected completion windows; a completion signal needs an explicit application definition of success. |
| Grafana | Candidate for evaluating and presenting the result signal | Validate the chosen data source, rule, and notification path together; an exception record alone is insufficient input. |
| OpenTelemetry | Instrumentation concepts for metrics | Define the accepted-result measurement, then choose collection, evaluation, and notification components. |
Infrai fits captured server exceptions, grouping, and basic lookup from an internal UI through one REST API with no SDK to install, plus one key and one bill for its backend capabilities. Any language that can send HTTP requests can call it. Sharing a single API key and unified billing reduces credential and billing administration when the importer uses other services on the platform. Its public discovery supplies schemas for mapping the local event to the documented capture contract. Keep that role focused on server-side exception evidence; use dedicated heartbeat monitoring for missed runs and an explicit evaluation and notification path for result alerts.
The limitation of this basic exception-store approach is that it cannot establish scheduled completion or useful output. It is not suitable as the sole alerting system for silent imports; choose Healthchecks for the heartbeat role and validate a result-alert pipeline separately. Choose a browser-focused service when source-map deobfuscation, crash symbolication, or session replay is a requirement. Those capabilities are outside this basic server-exception-store fit. Likewise, linking log records with trace identifiers should not be mistaken for a distributed trace query or span tree. Those are separate evaluation criteria.
Is a heartbeat enough, and does a rollback prove recovery?
A heartbeat answers a scheduling question. It does not define marketplace success. If the importer signals completion after reading a supplier file but before accepting listings, the check can stay green while useful output disappears. Put the completion signal after the work you intend it to certify, and retain a separate result rule when eligibility and acceptance can diverge.
Treat silence carefully.
A rollback changes the application release. It does not establish that the next scheduled window ran or that previously applied inventory writes are safe to repeat. Before replaying a batch, verify the application's idempotency boundary against the supplier batch and inventory mutation. An attempt ID is useful diagnostic context, but generating a new one for every retry does not by itself prevent duplicate business writes. A recovery decision needs a stable operation identity appropriate to the application's write semantics.
For the illustrative run, the operator should inspect the captured release and environment, confirm whether the batch actually contained eligible inventory, and check the next completion and accepted-result observations after recovery. If the older release also accepts zero from the same eligible input, the absence of new exceptions is weak evidence. Investigate the input contract and output conditions before closing the alert.
That is the practical rollback criterion: fresh useful output under the intended release and environment, with replay behavior understood. Error capture makes the failure explainable. Completion and result checks make recovery assessable.
Top comments (0)