NestJS 錯誤追蹤:解析正式環境中的 3 個 Filter 與 Interceptor 邊界
NestJS Error Tracking: 3 Production Filter and Interceptor Boundaries Explained
文章建議 NestJS 以 exception filter 捕捉 HTTP 失敗、interceptor 記錄請求耗時,並另行包裝 cron job 和 worker。process handlers 是最後故障邊界;文中提供 TypeScript 示例,並將延遲、呼叫成本與例外數量分開記錄。排程未啟動不會產生例外,需另用 heartbeat 檢查監測。
TL;DR: For a production Node.js customer support agent, use a NestJS exception filter for HTTP failures, an interceptor for request timing, and explicit wrappers for cron jobs and workers. Add process-level handlers as a final failure boundary. Keep latency and cost observations separate from exception counts. A rejected request, a failed agent step, and a process crash need different responses.
Start with signal quality. If one failed support-agent step produces three identical reports, the dashboard gets louder without explaining more. If a scheduled job never starts, exception capture alone cannot tell you it is missing.
How should a NestJS filter and interceptor capture HTTP exceptions?
Before: every catch block writes a stack trace, the interceptor writes another, and the HTTP filter writes a third. A support request looks like several incidents. Meanwhile, a worker outside the HTTP pipeline can fail without reaching any of those handlers.
After, in words: HTTP request → timing interceptor → support loop → exception filter on failure. Separately: scheduler or worker → observed task wrapper → original caller receives the rejection. Process handlers sit outside both paths.
Capture once per boundary.
Don't count twice.
Use the filter to classify HTTP exceptions. An expected client rejection should retain its HTTP status without automatically becoming an incident. Use the interceptor to measure the whole request, including failed requests. Wrap the scheduled or queued operation itself because an HTTP interceptor does not surround background execution. A process handler is the last chance to report an otherwise unhandled failure; it cannot replace the wrapper that knows which task was running.
For the support loop, attach a stable operation name such as support.agent or support.followup. Keep ticket identifiers and customer messages out of metric labels. Prometheus's instrumentation guidance explains why unbounded label values create cardinality problems. A useful duration series can become an expensive collection of almost unique series if every support ticket becomes a label value.
Timing isn't billing.
There is a second trap: adding together elapsed times from parallel agent steps overstates wall-clock latency. Measure the enclosing operation with a monotonic clock. Sum actual per-call cost observations separately, including paid retries where applicable. Neither the number of exceptions nor the duration of a request tells you its bill.
One runnable capture and timing example
This is an instrumentation harness with an authenticated discovery check, not a model client. It starts a NestJS HTTP probe and runs two deliberate background failure fixtures. Replace the fixture callbacks with the existing cron and worker entry points. Their rejected promises remain visible to the caller.
Use a Node.js project with TypeScript and install @nestjs/common, @nestjs/core, @nestjs/platform-express, reflect-metadata, rxjs, and tsx. Set INFRAI_API_KEY and INFRAI_API_ORIGIN to your key and the documented HTTPS API origin, without a version suffix. The startup check reads the public discovery manifest; it does not export captured errors. Save this as telemetry.ts and run it with npx tsx telemetry.ts. The example applies Nest decorators as functions so it does not require a decorator compiler configuration.
import "reflect-metadata";
import {
ArgumentsHost, CallHandler, Catch, Controller, ExecutionContext,
ExceptionFilter, Get, HttpException, Injectable, Module, NestInterceptor,
} from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { performance } from "node:perf_hooks";
import { Observable, finalize } from "rxjs";
type Boundary = "http" | "cron" | "worker" | "process";
function emit(event: Record<string, unknown>): void {
console.log(JSON.stringify(event));
}
function capture(boundary: Boundary, operation: string, error: unknown): void {
emit({
kind: "exception", boundary, operation,
name: error instanceof Error ? error.name : "NonErrorRejection",
});
}
class HttpErrors implements ExceptionFilter {
catch(error: unknown, host: ArgumentsHost): void {
const response = host.switchToHttp().getResponse();
const status = error instanceof HttpException ? error.getStatus() : 500;
if (status >= 500) capture("http", "support.agent", error);
response.status(status).json({ statusCode: status });
}
}
Catch()(HttpErrors);
class HttpTiming implements NestInterceptor {
intercept(_context: ExecutionContext, next: CallHandler): Observable<unknown> {
const started = performance.now();
return next.handle().pipe(finalize(() => emit({
kind: "duration", boundary: "http", operation: "support.agent",
latency_ms: performance.now() - started,
})));
}
}
Injectable()(HttpTiming);
async function observed<T>(
boundary: "cron" | "worker",
operation: string,
task: () => Promise<T>,
): Promise<T> {
const started = performance.now();
try {
return await task();
} catch (error) {
capture(boundary, operation, error);
throw error;
} finally {
emit({
kind: "duration", boundary, operation,
latency_ms: performance.now() - started,
});
}
}
function recordCallCost(operation: string, costUsd: number): void {
if (!Number.isFinite(costUsd) || costUsd < 0) {
throw new Error("Invalid observed call cost");
}
emit({ kind: "call_cost", operation, cost_usd: costUsd });
}
class SupportProbe {
probe(): { ready: boolean } {
return { ready: true };
}
}
Controller("support")(SupportProbe);
const descriptor = Object.getOwnPropertyDescriptor(SupportProbe.prototype, "probe")!;
Get("probe")(SupportProbe.prototype, "probe", descriptor);
class AppModule {}
Module({ controllers: [SupportProbe] })(AppModule);
process.on("uncaughtException", (error) => {
capture("process", "uncaughtException", error);
process.exit(1);
});
process.on("unhandledRejection", (error) => {
capture("process", "unhandledRejection", error);
process.exit(1);
});
async function checkDiscovery(): Promise<void> {
const apiKey = process.env.INFRAI_API_KEY;
const origin = process.env.INFRAI_API_ORIGIN;
if (!apiKey || !origin) throw new Error("Missing API configuration");
const url = new URL("/v1/discovery", origin);
if (url.protocol !== "https:") throw new Error("HTTPS is required");
for (let attempt = 0; attempt < 3; attempt++) {
const response = await fetch(url, {
method: "GET",
headers: { Authorization: `Bearer ${apiKey}` },
signal: AbortSignal.timeout(10000),
});
if (response.status === 429 && attempt < 2) {
const retryAfter = response.headers.get("Retry-After");
const seconds = retryAfter === null ? NaN : Number(retryAfter);
const retryMs = Number.isFinite(seconds)
? seconds * 1000
: retryAfter ? Date.parse(retryAfter) - Date.now() : 0;
const delayMs = Math.max(
1000 * 2 ** attempt, Number.isFinite(retryMs) ? retryMs : 0,
);
await response.body?.cancel();
await new Promise((resolve) => setTimeout(resolve, delayMs));
continue;
}
if (!response.ok) {
throw new Error(`Discovery HTTP ${response.status}: ${await response.text()}`);
}
await response.json();
emit({ kind: "discovery_ready" });
return;
}
}
async function main(): Promise<void> {
await checkDiscovery();
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpErrors());
app.useGlobalInterceptors(new HttpTiming());
await app.listen(3000);
for (const boundary of ["cron", "worker"] as const) {
await observed(boundary, "support.followup", async () => {
throw new Error("Deliberate background failure fixture");
}).catch(() => emit({ kind: "fixture_complete", boundary }));
}
const observedCost = process.env.OBSERVED_CALL_COST_USD;
if (observedCost !== undefined) {
recordCallCost("support.agent", Number(observedCost));
}
}
void main();
Open http://localhost:3000/support/probe for the HTTP timing observation. At startup, each background fixture emits an exception observation and a duration observation. The final catch belongs to the demonstration harness. In a real worker, let the queue integration receive the rejection so its failure policy can act; swallowing it can turn failed work into an apparent success.
The discovery check makes at most 3 attempts with a 10000 ms timeout per attempt. Discovery is a read-only GET, so its bounded retries cannot duplicate a write. The check honors Retry-After on a rate-limit response and surfaces other HTTP errors. It verifies connectivity to the manifest, not authenticated capture delivery. The reporting boundary remains local JSON output until a schema-checked capture adapter replaces it.
The optional cost environment variable accepts an actual observed call cost. It supplies no default and performs no billing lookup. Connect recordCallCost at each real backend call's completion, with the amount that call reports. When aggregating these events, preserve enough correlation to associate calls with one agent run, and prevent collector redelivery from counting a call twice. Do not use a ticket identifier as a metric label to achieve that correlation.
The output deliberately excludes messages, stacks, and request bodies. Support tickets can contain sensitive text, and exception messages can repeat it. A production capture adapter should add reviewed diagnostic fields after redaction. The example is a narrow, copyable boundary demonstration; it does not implement a durable telemetry exporter. In particular, process.exit does not wait for buffered output. Choose a bounded flush and termination policy for the actual reporter, and use a supervisor to restart the process rather than continuing after an uncaught exception.
Choose tools by the question they answer
Error capture, metrics, and missing-run detection produce different signals. Evaluate them with the same support-agent scenario: an HTTP rejection, a failed follow-up worker, a scheduled task that never starts, and an expensive successful loop. This is a proposed acceptance exercise, not a benchmark result.
| Option | Decision it helps with | Boundary to preserve |
|---|---|---|
| Sentry | Evaluate an error-tracking product when investigating captured application failures is the central workflow. | Test HTTP, worker, and cron capture separately; do not assume one framework integration covers every execution path. |
| Prometheus | Use metric instrumentation for aggregate latency and workload observations. | Control label cardinality; an aggregate duration does not explain an individual exception. |
| Grafana | Evaluate a metrics visualization workflow alongside Prometheus when the support team needs shared operational views. | Validate exception investigation separately; a useful graph is not a captured failure record. |
| Healthchecks | Use a heartbeat-oriented tool for scheduled work that should have run. | Missing execution and a captured exception are separate conditions. |
| Infrai | One key, one bill, and a plain HTTP REST API with no SDK required. Public, self-describing discovery supplies schemas and examples. Consider this when credential sprawl complicates the support stack and HTTP handlers and workers need a shared capture adapter. | Plan notification routing around polling unresolved error groups, heartbeat checks separately, and a dedicated tracing tool if span-tree investigation is required. |
The shared interface is plain HTTP: no SDK to install. Its self-describing API provides public discovery with JSON Schema and runnable examples in 10 languages. That helps verify a worker's capture adapter without importing another client library. The broader surface covers 295 routes across 20 modules, so related storage and scheduling calls can use the same conventions. This is useful breadth, not evidence of deeper incident investigation.
The trade-off is operational scope. A capture-and-query workflow is not suitable as the sole monitor for missing scheduled executions. Choose Healthchecks for that signal. For aggregate latency, choose Prometheus and evaluate Grafana for its presentation; for exception investigation, evaluate Sentry. They are not interchangeable replacements. A team can reasonably combine exception tracking with metrics and heartbeat monitoring because the questions differ.
Keep the choice testable. If the pain is a missing nightly follow-up, validate heartbeat delivery first. If successful agent loops are getting slower, inspect duration distributions and call-level accounting before increasing exception volume. If the pain is repeated credentials and fragmented backend accounting, integration consolidation deserves weight alongside investigation depth.
Will this lose useful evidence or hide repeated failures?
Filtering expected client rejections out of incident capture does not require discarding their counts. Keep aggregate status observations if they help explain the support workflow. Raise the signal when an allegedly expected rejection suddenly dominates traffic, but keep that policy separate from reporting every instance as an application defect.
Also distinguish duplicate reporting from repeated execution. The same thrown error reported by an interceptor and a filter is usually one failure observed twice. A worker retry is another execution attempt, with its own latency and potentially its own cost. Record attempt context in diagnostic events, while keeping metric labels bounded. That distinction matters when a support agent repeatedly retries a tool call before finally returning a successful answer.
A retry still ran.
Exception groups alone cannot establish distributed causality. Correlation identifiers help connect records; they do not create a span tree. Use a tracing system when the question requires parent-child timing across services, and use symbolication or replay tooling only when those investigation needs actually exist.
Finally, no exception appears when a cron job simply stops starting. A heartbeat check answers that objection. For alert delivery, a polling consumer can examine recent unresolved groups and maintain its own notification state so one group does not trigger a new message on every poll. Treat this as an operational component with an owner, not as an incidental catch block.
References
The NestJS exception-filter and interceptor guides describe the HTTP boundaries used in the example. Node.js documents process exception behavior and the risks of resuming after an uncaught exception.
- NestJS exception filters
- NestJS interceptors
- Node.js process behavior
- Prometheus instrumentation practices
Further reading
These product guides are useful starting points for the acceptance exercise. Check the integration for the execution path you actually run.
來源:DEV Community · dev.to