Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/web/src/app/api/trpc/[trpc]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ const handler = (req: Request) => {
// procedure chose. The input never goes along.
onError: ({ error, path, ctx }) => {
if (error.code !== "INTERNAL_SERVER_ERROR") return;
void captureError(error.cause ?? error, {
const fault = error.cause ?? error;
console.error("unhandled trpc error", path, fault);
void captureError(fault, {
teamId: ctx?.teamId,
tags: path ? { procedure: path } : {},
});
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/server/routers/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -761,7 +761,8 @@ export function createSettingsRouter(
.update(schema.teamInvitations)
.set({ lastSentAt: invite.lastSentAt, sendCount: invite.sendCount })
.where(eq(schema.teamInvitations.id, invite.id));
throw await inviteRefusal("INTERNAL_SERVER_ERROR", "sendFailed");
// Not INTERNAL_SERVER_ERROR: the browser never reads a fault's own message.
throw await inviteRefusal("SERVICE_UNAVAILABLE", "sendFailed");
}
await recordAudit(ctx, {
action: "invitation.resent",
Expand Down
17 changes: 16 additions & 1 deletion apps/web/src/server/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,22 @@ export async function createContext({ headers }: { headers: Headers }): Promise<
return { ...shared, teamId: membership?.teamId ?? null, role: membership?.role ?? null };
}

const t = initTRPC.context<Context>().create({ transformer: superjson });
/** What the browser reads for a fault (INTERNAL_SERVER_ERROR) in place of its own text. */
export const FAULT_MESSAGE =
"Something went wrong. Try again, or contact support if it keeps happening.";

// A fault's text can carry SQL, table and column names and query parameters,
// so its message and stack reach the browser only under `next dev`; the
// route's onError logs and reports it whole. Passed to tRPC too: its default
// (any NODE_ENV but production) would send the stack in tests.
const isDev = process.env.NODE_ENV === "development";

const t = initTRPC.context<Context>().create({
transformer: superjson,
isDev,
errorFormatter: ({ shape, error }) =>
error.code === "INTERNAL_SERVER_ERROR" && !isDev ? { ...shape, message: FAULT_MESSAGE } : shape,
});

export const router = t.router;
export const createCallerFactory = t.createCallerFactory;
Expand Down
51 changes: 50 additions & 1 deletion apps/web/test/error-tracking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const h = vi.hoisted(() => ({
captureError: vi.fn(async () => {}),
sdk: { start: vi.fn(), captureException: vi.fn() },
contextError: undefined as Error | undefined,
queryError: undefined as Error | undefined,
}));

vi.mock("@millionsend/core/error-tracking-node", () => ({
Expand All @@ -18,7 +19,19 @@ vi.mock("@/server/trpc", async (importOriginal) => {
...actual,
createContext: async () => {
if (h.contextError) throw h.contextError;
return { db: null as never, session: null, teamId: null, role: null };
const { queryError } = h;
if (!queryError) return { db: null as never, session: null, teamId: null, role: null };
// A signed-in owner whose every query fails with queryError.
return {
db: {
select: () => {
throw queryError;
},
} as never,
session: { user: { id: "user-1", email: "owner@example.com", name: "Owner" } },
teamId: "team-1",
role: "owner" as const,
};
},
};
});
Expand All @@ -35,12 +48,15 @@ const { POST: tunnel } = await import("@/app/api/client-errors/route");
const { default: RootLayout } = await import("@/app/layout");
const { ErrorTracking } = await import("@/components/error-tracking");
const { reportClientError, startClientErrorTracking } = await import("@/lib/client-errors");
const { FAULT_MESSAGE } = await import("@/server/trpc");
const { unstorableValueMessage } = await import("@millionsend/core");

const DSN = "https://public@errors.example.com/7";

beforeEach(() => {
h.captureError.mockClear();
h.contextError = undefined;
h.queryError = undefined;
});
afterEach(() => {
vi.unstubAllEnvs();
Expand Down Expand Up @@ -73,13 +89,46 @@ describe("server errors", () => {
expect((await call()).status).toBe(401);
expect(h.captureError).not.toHaveBeenCalled();

vi.spyOn(console, "error").mockImplementation(() => {});
h.contextError = new Error("connection refused");
expect((await call()).status).toBe(500);
expect(h.captureError).toHaveBeenCalledExactlyOnceWith(h.contextError, {
teamId: undefined,
tags: { procedure: "apiKeys.list" },
});
});

it("answers a procedure's fault in general words, logging and reporting the error itself", async () => {
vi.stubEnv("APP_BASE_URL", "https://app.example.com");
const log = vi.spyOn(console, "error").mockImplementation(() => {});
h.queryError = new Error('Failed query: select "secret" from "keys" where "team_id" = $1');
const res = await trpcGet(new Request("https://app.example.com/api/trpc/apiKeys.list"));
expect(res.status).toBe(500);
const body = await res.text();
expect(body).not.toContain("Failed query");
expect(body).not.toContain("secret");
expect(JSON.parse(body)).toMatchObject({
error: { json: { message: FAULT_MESSAGE, data: { code: "INTERNAL_SERVER_ERROR" } } },
});
expect(h.captureError).toHaveBeenCalledExactlyOnceWith(h.queryError, {
teamId: "team-1",
tags: { procedure: "apiKeys.list" },
});
expect(log.mock.calls.flat()).toContain(h.queryError);
});

it("passes a refusal's own message on, unreported", async () => {
vi.stubEnv("APP_BASE_URL", "https://app.example.com");
h.queryError = Object.assign(new Error("invalid byte sequence"), { code: "22021" });
const res = await trpcGet(new Request("https://app.example.com/api/trpc/apiKeys.list"));
expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({
error: {
json: { message: unstorableValueMessage(h.queryError), data: { code: "BAD_REQUEST" } },
},
});
expect(h.captureError).not.toHaveBeenCalled();
});
});

describe("the browser", () => {
Expand Down
2 changes: 1 addition & 1 deletion apps/web/test/invitations-router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ describe("settings.invitations send accounting", () => {
const failing = mailCaller("owner1", teamId, "owner", { failing: true });
await expect(
failing.caller.settings.invitations.resend({ id: created.id }),
).rejects.toMatchObject({ code: "INTERNAL_SERVER_ERROR" });
).rejects.toMatchObject({ code: "SERVICE_UNAVAILABLE" });
const [row] = await db
.select()
.from(schema.teamInvitations)
Expand Down
Loading