Skip to content

Open-source status page, incident response and uptime monitoring

Centralize tRPC error handling and Sentry filtering (#2391)

Maximilian Kaskeec5cd6669254
diff --git a/apps/dashboard/sentry.edge.config.ts b/apps/dashboard/sentry.edge.config.ts
index baae24f36..72cfb4989 100644
--- a/apps/dashboard/sentry.edge.config.ts
+++ b/apps/dashboard/sentry.edge.config.ts
@@ -2,15 +2,8 @@
// The config you add here will be used whenever one of the edge features is loaded.
// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+import { isExpectedTRPCError } from "@openstatus/api/src/trpc-errors";
import * as Sentry from "@sentry/nextjs";
-import { TRPCError } from "@trpc/server";
-
-// tRPC error codes that should not be reported to Sentry (expected client errors)
-const IGNORED_TRPC_CODES: TRPCError["code"][] = [
- "UNAUTHORIZED",
- "NOT_FOUND",
- "BAD_REQUEST",
-];
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
@@ -23,10 +16,7 @@ Sentry.init({
integrations: [Sentry.captureConsoleIntegration({ levels: ["error"] })],
beforeSend(event, hint) {
- if (
- hint.originalException instanceof TRPCError &&
- IGNORED_TRPC_CODES.includes(hint.originalException.code)
- ) {
+ if (isExpectedTRPCError(hint.originalException)) {
return null;
}
return event;
diff --git a/apps/dashboard/sentry.server.config.ts b/apps/dashboard/sentry.server.config.ts
index 4dbeb370a..0ab6effc1 100644
--- a/apps/dashboard/sentry.server.config.ts
+++ b/apps/dashboard/sentry.server.config.ts
@@ -2,15 +2,8 @@
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+import { isExpectedTRPCError } from "@openstatus/api/src/trpc-errors";
import * as Sentry from "@sentry/nextjs";
-import { TRPCError } from "@trpc/server";
-
-// tRPC error codes that should not be reported to Sentry (expected client errors)
-const IGNORED_TRPC_CODES: TRPCError["code"][] = [
- "UNAUTHORIZED",
- "NOT_FOUND",
- "BAD_REQUEST",
-];
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
@@ -23,10 +16,7 @@ Sentry.init({
integrations: [Sentry.captureConsoleIntegration({ levels: ["error"] })],
beforeSend(event, hint) {
- if (
- hint.originalException instanceof TRPCError &&
- IGNORED_TRPC_CODES.includes(hint.originalException.code)
- ) {
+ if (isExpectedTRPCError(hint.originalException)) {
return null;
}
return event;
diff --git a/apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.ts b/apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.ts
index 0ebe36093..79a9979f9 100644
--- a/apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.ts
+++ b/apps/dashboard/src/app/api/trpc/lambda/[trpc]/route.ts
@@ -1,9 +1,10 @@
import { appRouter, createTRPCContext } from "@openstatus/api";
+import { createTRPCOnError } from "@openstatus/api/src/trpc-errors";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import type { NextRequest } from "next/server";
import { auth } from "@/lib/auth";
-import { createOnError, guardTRPCSource } from "@/lib/trpc/shared";
+import { guardTRPCSource } from "@/lib/trpc/shared";
// Runs on the Node.js runtime (Vercel Fluid compute). The whole tRPC surface
// is served here — several routers pull Node-only deps (@slack/web-api, email
@@ -18,7 +19,7 @@ const handler = (req: NextRequest) => {
router: appRouter,
req: req,
createContext: () => createTRPCContext({ req, auth }),
- onError: createOnError("lambda"),
+ onError: createTRPCOnError("lambda"),
});
};
diff --git a/apps/dashboard/src/lib/trpc/shared.ts b/apps/dashboard/src/lib/trpc/shared.ts
index b80281e19..110c9eb5b 100644
--- a/apps/dashboard/src/lib/trpc/shared.ts
+++ b/apps/dashboard/src/lib/trpc/shared.ts
@@ -33,16 +33,6 @@ export const sentryLoggerLink = (): TRPCLink<AppRouter> =>
},
});
-/**
- * Shared onError handler for tRPC route handlers.
- */
-export function createOnError(label: string) {
- return ({ error }: { error: { code: string; message: string } }) => {
- console.log(`Error in tRPC handler (${label})`);
- console.error(error);
- };
-}
-
/**
* Filter out requests that don't come from our tRPC clients.
* Our server and client links always set `x-trpc-source`.
diff --git a/apps/status-page/sentry.edge.config.ts b/apps/status-page/sentry.edge.config.ts
index baae24f36..72cfb4989 100644
--- a/apps/status-page/sentry.edge.config.ts
+++ b/apps/status-page/sentry.edge.config.ts
@@ -2,15 +2,8 @@
// The config you add here will be used whenever one of the edge features is loaded.
// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+import { isExpectedTRPCError } from "@openstatus/api/src/trpc-errors";
import * as Sentry from "@sentry/nextjs";
-import { TRPCError } from "@trpc/server";
-
-// tRPC error codes that should not be reported to Sentry (expected client errors)
-const IGNORED_TRPC_CODES: TRPCError["code"][] = [
- "UNAUTHORIZED",
- "NOT_FOUND",
- "BAD_REQUEST",
-];
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
@@ -23,10 +16,7 @@ Sentry.init({
integrations: [Sentry.captureConsoleIntegration({ levels: ["error"] })],
beforeSend(event, hint) {
- if (
- hint.originalException instanceof TRPCError &&
- IGNORED_TRPC_CODES.includes(hint.originalException.code)
- ) {
+ if (isExpectedTRPCError(hint.originalException)) {
return null;
}
return event;
diff --git a/apps/status-page/sentry.server.config.ts b/apps/status-page/sentry.server.config.ts
index 4dbeb370a..0ab6effc1 100644
--- a/apps/status-page/sentry.server.config.ts
+++ b/apps/status-page/sentry.server.config.ts
@@ -2,15 +2,8 @@
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+import { isExpectedTRPCError } from "@openstatus/api/src/trpc-errors";
import * as Sentry from "@sentry/nextjs";
-import { TRPCError } from "@trpc/server";
-
-// tRPC error codes that should not be reported to Sentry (expected client errors)
-const IGNORED_TRPC_CODES: TRPCError["code"][] = [
- "UNAUTHORIZED",
- "NOT_FOUND",
- "BAD_REQUEST",
-];
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
@@ -23,10 +16,7 @@ Sentry.init({
integrations: [Sentry.captureConsoleIntegration({ levels: ["error"] })],
beforeSend(event, hint) {
- if (
- hint.originalException instanceof TRPCError &&
- IGNORED_TRPC_CODES.includes(hint.originalException.code)
- ) {
+ if (isExpectedTRPCError(hint.originalException)) {
return null;
}
return event;
diff --git a/apps/status-page/src/app/api/trpc/lambda/[trpc]/route.ts b/apps/status-page/src/app/api/trpc/lambda/[trpc]/route.ts
index f3c1eef83..25e6eb1bf 100644
--- a/apps/status-page/src/app/api/trpc/lambda/[trpc]/route.ts
+++ b/apps/status-page/src/app/api/trpc/lambda/[trpc]/route.ts
@@ -1,9 +1,10 @@
import { appRouter, createTRPCContext } from "@openstatus/api";
+import { createTRPCOnError } from "@openstatus/api/src/trpc-errors";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import type { NextRequest } from "next/server";
import { auth } from "../../../../../lib/auth";
-import { createOnError, guardTRPCSource } from "../../../../../lib/trpc/shared";
+import { guardTRPCSource } from "../../../../../lib/trpc/shared";
// Runs on the Node.js runtime (Vercel Fluid compute). The whole tRPC surface
// is served here — several routers pull Node-only deps (@slack/web-api, email
@@ -18,7 +19,7 @@ const handler = (req: NextRequest) => {
router: appRouter,
req: req,
createContext: () => createTRPCContext({ req, auth }),
- onError: createOnError("lambda"),
+ onError: createTRPCOnError("lambda"),
});
};
diff --git a/apps/status-page/src/lib/trpc/shared.ts b/apps/status-page/src/lib/trpc/shared.ts
index f0dc5fa2d..3519e0b4f 100644
--- a/apps/status-page/src/lib/trpc/shared.ts
+++ b/apps/status-page/src/lib/trpc/shared.ts
@@ -2,7 +2,6 @@ import type { AppRouter } from "@openstatus/api";
import * as Sentry from "@sentry/nextjs";
import type { HTTPBatchLinkOptions, HTTPHeaders, TRPCLink } from "@trpc/client";
import { httpBatchLink, loggerLink } from "@trpc/client";
-import type { TRPCError } from "@trpc/server";
import superjson from "superjson";
/**
@@ -34,16 +33,6 @@ export const sentryLoggerLink = (): TRPCLink<AppRouter> =>
},
});
-/**
- * Shared onError handler for tRPC route handlers.
- */
-export function createOnError(label: string) {
- return ({ error }: { error: TRPCError }) => {
- console.log(`Error in tRPC handler (${label})`);
- console.error(error);
- };
-}
-
/**
* Filter out requests that don't come from our tRPC clients.
* Our server and client links always set `x-trpc-source`.
diff --git a/apps/web/sentry.edge.config.ts b/apps/web/sentry.edge.config.ts
index 1d534fe9d..9d1acf6a2 100644
--- a/apps/web/sentry.edge.config.ts
+++ b/apps/web/sentry.edge.config.ts
@@ -2,18 +2,11 @@
// The config you add here will be used whenever one of the edge features is loaded.
// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+import { isExpectedTRPCError } from "@openstatus/api/src/trpc-errors";
import * as Sentry from "@sentry/nextjs";
-import { TRPCError } from "@trpc/server";
import { env } from "@/env";
-// tRPC error codes that should not be reported to Sentry (expected client errors)
-const IGNORED_TRPC_CODES: TRPCError["code"][] = [
- "UNAUTHORIZED",
- "NOT_FOUND",
- "BAD_REQUEST",
-];
-
Sentry.init({
dsn: env.NEXT_PUBLIC_SENTRY_DSN,
@@ -25,10 +18,7 @@ Sentry.init({
integrations: [Sentry.captureConsoleIntegration({ levels: ["error"] })],
beforeSend(event, hint) {
- if (
- hint.originalException instanceof TRPCError &&
- IGNORED_TRPC_CODES.includes(hint.originalException.code)
- ) {
+ if (isExpectedTRPCError(hint.originalException)) {
return null;
}
return event;
diff --git a/apps/web/sentry.server.config.ts b/apps/web/sentry.server.config.ts
index 275869259..b1f913250 100644
--- a/apps/web/sentry.server.config.ts
+++ b/apps/web/sentry.server.config.ts
@@ -2,18 +2,11 @@
// The config you add here will be used whenever the server handles a request.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
+import { isExpectedTRPCError } from "@openstatus/api/src/trpc-errors";
import * as Sentry from "@sentry/nextjs";
-import { TRPCError } from "@trpc/server";
import { env } from "@/env";
-// tRPC error codes that should not be reported to Sentry (expected client errors)
-const IGNORED_TRPC_CODES: TRPCError["code"][] = [
- "UNAUTHORIZED",
- "NOT_FOUND",
- "BAD_REQUEST",
-];
-
Sentry.init({
dsn: env.NEXT_PUBLIC_SENTRY_DSN,
@@ -25,10 +18,7 @@ Sentry.init({
integrations: [Sentry.captureConsoleIntegration({ levels: ["error"] })],
beforeSend(event, hint) {
- if (
- hint.originalException instanceof TRPCError &&
- IGNORED_TRPC_CODES.includes(hint.originalException.code)
- ) {
+ if (isExpectedTRPCError(hint.originalException)) {
return null;
}
return event;
diff --git a/apps/web/src/app/api/trpc/lambda/[trpc]/route.ts b/apps/web/src/app/api/trpc/lambda/[trpc]/route.ts
index 477427b3d..843b92722 100644
--- a/apps/web/src/app/api/trpc/lambda/[trpc]/route.ts
+++ b/apps/web/src/app/api/trpc/lambda/[trpc]/route.ts
@@ -1,8 +1,9 @@
import { appRouter, createTRPCContext } from "@openstatus/api";
+import { createTRPCOnError } from "@openstatus/api/src/trpc-errors";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import type { NextRequest } from "next/server";
-import { createOnError, guardTRPCSource } from "../../../../../trpc/shared";
+import { guardTRPCSource } from "../../../../../trpc/shared";
// Runs on the Node.js runtime (Vercel Fluid compute). The whole tRPC surface
// is served here — several routers pull Node-only deps (@slack/web-api, email
@@ -17,7 +18,7 @@ const handler = (req: NextRequest) => {
router: appRouter,
req: req,
createContext: () => createTRPCContext({ req }),
- onError: createOnError("lambda"),
+ onError: createTRPCOnError("lambda"),
});
};
diff --git a/apps/web/src/trpc/shared.ts b/apps/web/src/trpc/shared.ts
index 5696444e7..424664f91 100644
--- a/apps/web/src/trpc/shared.ts
+++ b/apps/web/src/trpc/shared.ts
@@ -33,16 +33,6 @@ export const sentryLoggerLink = (): TRPCLink<AppRouter> =>
},
});
-/**
- * Shared onError handler for tRPC route handlers.
- */
-export function createOnError(label: string) {
- return ({ error }: { error: { code: string; message: string } }) => {
- console.log(`Error in tRPC handler (${label})`);
- console.error(error);
- };
-}
-
/**
* Filter out requests that don't come from our tRPC clients.
* Our server and client links always set `x-trpc-source`.
diff --git a/packages/api/src/trpc-errors.test.ts b/packages/api/src/trpc-errors.test.ts
new file mode 100644
index 000000000..c367350f7
--- /dev/null
+++ b/packages/api/src/trpc-errors.test.ts
@@ -0,0 +1,102 @@
+import { expect } from "@std/expect";
+import { describe, test } from "@std/testing/bdd";
+import { TRPCError } from "@trpc/server";
+
+import {
+ EXPECTED_TRPC_CODES,
+ createTRPCOnError,
+ isExpectedTRPCError,
+ isExpectedTRPCErrorCode,
+} from "./trpc-errors";
+
+// Simulates the cross-bundle case: a TRPCError from the app bundle whose class
+// identity differs from this module's `@trpc/server`, so only name + code match.
+function fakeTRPCError(code: string): unknown {
+ return Object.assign(new Error("boom"), { name: "TRPCError", code });
+}
+
+function captureConsole(fn: () => void): { error: number; log: number } {
+ const origError = console.error;
+ const origLog = console.log;
+ let error = 0;
+ let log = 0;
+ console.error = () => {
+ error++;
+ };
+ console.log = () => {
+ log++;
+ };
+ try {
+ fn();
+ } finally {
+ console.error = origError;
+ console.log = origLog;
+ }
+ return { error, log };
+}
+
+describe("isExpectedTRPCErrorCode", () => {
+ test("true for every expected client code", () => {
+ for (const code of EXPECTED_TRPC_CODES) {
+ expect(isExpectedTRPCErrorCode(code)).toBe(true);
+ }
+ });
+
+ test("false for server errors", () => {
+ expect(isExpectedTRPCErrorCode("INTERNAL_SERVER_ERROR")).toBe(false);
+ expect(isExpectedTRPCErrorCode("TIMEOUT")).toBe(false);
+ });
+});
+
+describe("isExpectedTRPCError", () => {
+ test("true for a real TRPCError with an expected code", () => {
+ const err = new TRPCError({ code: "NOT_FOUND", message: "not found" });
+ expect(isExpectedTRPCError(err)).toBe(true);
+ });
+
+ test("false for a real TRPCError with a server-error code", () => {
+ const err = new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
+ expect(isExpectedTRPCError(err)).toBe(false);
+ });
+
+ test("true for a cross-bundle TRPCError matched by name + code", () => {
+ expect(isExpectedTRPCError(fakeTRPCError("NOT_FOUND"))).toBe(true);
+ });
+
+ test("false for a cross-bundle TRPCError with a server-error code", () => {
+ expect(isExpectedTRPCError(fakeTRPCError("INTERNAL_SERVER_ERROR"))).toBe(
+ false,
+ );
+ });
+
+ test("false for a plain Error that is not a TRPCError", () => {
+ expect(isExpectedTRPCError(new Error("NOT_FOUND"))).toBe(false);
+ });
+
+ test("false for non-error values", () => {
+ expect(isExpectedTRPCError(null)).toBe(false);
+ expect(isExpectedTRPCError(undefined)).toBe(false);
+ expect(isExpectedTRPCError("NOT_FOUND")).toBe(false);
+ expect(isExpectedTRPCError({ code: "NOT_FOUND" })).toBe(false);
+ });
+});
+
+describe("createTRPCOnError", () => {
+ test("does not log expected client errors", () => {
+ const onError = createTRPCOnError("lambda");
+ const counts = captureConsole(() =>
+ onError({ error: { code: "NOT_FOUND", message: "not found" } }),
+ );
+ expect(counts.error).toBe(0);
+ expect(counts.log).toBe(0);
+ });
+
+ test("logs genuine server errors", () => {
+ const onError = createTRPCOnError("lambda");
+ const counts = captureConsole(() =>
+ onError({ error: { code: "INTERNAL_SERVER_ERROR", message: "boom" } }),
+ );
+ expect(counts.error).toBe(1);
+ expect(counts.log).toBe(1);
+ });
+});
diff --git a/packages/api/src/trpc-errors.ts b/packages/api/src/trpc-errors.ts
new file mode 100644
index 000000000..d4c4ea2ec
--- /dev/null
+++ b/packages/api/src/trpc-errors.ts
@@ -0,0 +1,47 @@
+import type { TRPCError } from "@trpc/server";
+
+/**
+ * tRPC error codes that map to 4xx client errors. These are expected outcomes
+ * (missing resource, bad input, unauthorized), not bugs, so they should not be
+ * reported to Sentry.
+ */
+export const EXPECTED_TRPC_CODES: readonly TRPCError["code"][] = [
+ "BAD_REQUEST",
+ "UNAUTHORIZED",
+ "FORBIDDEN",
+ "NOT_FOUND",
+ "CONFLICT",
+ "PRECONDITION_FAILED",
+ "TOO_MANY_REQUESTS",
+];
+
+export function isExpectedTRPCErrorCode(code: TRPCError["code"]): boolean {
+ return EXPECTED_TRPC_CODES.includes(code);
+}
+
+/**
+ * Duck-typed guard for Sentry's `beforeSend`. Matches on the error name + code
+ * rather than `instanceof TRPCError`: the thrown error comes from the app
+ * bundle, whose `@trpc/server` class identity differs from the copy an
+ * instrumentation config would import at runtime, so `instanceof` gives false
+ * negatives.
+ */
+export function isExpectedTRPCError(err: unknown): err is TRPCError {
+ return (
+ err instanceof Error &&
+ err.name === "TRPCError" &&
+ isExpectedTRPCErrorCode((err as TRPCError).code)
+ );
+}
+
+/**
+ * tRPC route-handler `onError`. Logs genuine server errors but drops expected
+ * client errors, so Sentry's `captureConsoleIntegration` never reports them.
+ */
+export function createTRPCOnError(label: string) {
+ return ({ error }: { error: Pick<TRPCError, "code" | "message"> }) => {
+ if (isExpectedTRPCErrorCode(error.code)) return;
+ console.log(`Error in tRPC handler (${label})`);
+ console.error(error);
+ };
+}