Skip to content
This repository was archived by the owner on Oct 25, 2026. It is now read-only.

Latest commit

 

History

History
1706 lines (1354 loc) · 67.3 KB

ERROR_HANDLING.md

File metadata and controls

1706 lines (1354 loc) · 67.3 KB

Error Handling Guide — WorkForge

Status: Proposal / standard-to-adopt. Scope: Next.js 15 (App Router) · tRPC v11 · Drizzle (postgres-js) · better-auth · TanStack Query · Zod · sonner. Audience: everyone writing code in this repo. Treat the "Rules" and "Review checklist" sections as binding.

This document is the single source of truth for how errors are produced, propagated, logged, and shown to users in WorkForge. It is written against the actual state of this codebase — every anti-pattern in §9 is real, with file references.


Table of contents

  1. Executive summary: what is broken today
  2. Core principles
  3. The error model
  4. Layer 1 — Database & data access
  5. Layer 2 — tRPC procedures (the most important layer)
  6. Layer 3 — tRPC infrastructure: middleware, formatter, logging
  7. Layer 4 — Route handlers (app/api/**)
  8. Layer 5 — Middleware (src/middleware.ts)
  9. Layer 6 — Server Components & RSC data fetching
  10. Layer 7 — React error boundaries (error.tsx)
  11. Layer 8 — Client data layer (TanStack Query + tRPC)
  12. Layer 9 — Forms & user-facing feedback
  13. Layer 10 — External services (email, Cloudinary, third-party APIs)
  14. Logging & observability
  15. Anti-patterns found in this codebase
  16. Adoption plan
  17. PR review checklist

1. Executive summary: what is broken today

# Problem Where Severity
1 try/catch swallows deliberate TRPCErrors and rewrites them all to INTERNAL_SERVER_ERROR: "Something went wrong while runnig the code." — users never see "Organization not found", "email already exists", etc. src/server/api/routers/auth.ts — all 4 procedures Critical
2 catch returns undefined, so a failed query resolves as a successful response with no data. Failure is indistinguishable from empty. src/server/api/routers/org.ts:55-58 Critical
3 Zero React error boundaries — no error.tsx, no global-error.tsx, no loading.tsx anywhere in src/app. Any RSC throw = blank screen / framework error page. whole app Critical
4 Production errors are never logged. onError in the tRPC handler is undefined when NODE_ENV !== "development". src/app/api/trpc/[trpc]/route.ts:19-27 Critical
5 Root layout does unguarded data fetching (api.organization.getUserOrgDetails()), so one DB blip takes down every page, including public marketing pages. src/app/layout.tsx:29-35 High
6 middleware.ts has no try/catch around auth.api.getSession. A session-store failure 500s every matched route — a total outage. src/middleware.ts:38 High
7 createWorkspace performs 4 sequential writes with no transaction. Partial failure leaves orphaned organizations. src/server/api/routers/auth.ts:286-320 High
8 Non-null assertions on values that are genuinely nullable (members[0]!, activeOrganizationSlug!, .split("@")[1]) despite noUncheckedIndexedAccess: true. Each is a latent TypeError. org.ts:48-51, auth.ts:48, team/invite.tsx:35 High
9 No global TanStack Query error handling, no retry policy — 4xx errors get retried, and rejected queries silently render empty UI. src/trpc/query-client.ts Medium
10 Client mutations console.error + setStatus("error") with no toast — the user sees nothing happen. team/invite.tsx:53-56, onboard/company/page.tsx:159-162 Medium
11 console.log({ err }) used as error logging in 22 places — unstructured, unsearchable, wrong stream. repo-wide Medium
12 /api/uploads reads formData.get("logo") but useUpload sends "file" — a silent 400 contract mismatch. api/uploads/route.ts:15 vs hooks/use-upload.ts:29 Medium
13 Route handlers parse bodies with await request.json() + as casts, no Zod. Malformed JSON throws an unhandled 500. api/set-tenant/route.ts:8 Medium
14 External calls (Resend, nodemailer, Cloudinary) have no timeout, no retry, no circuit breaking. Email-provider latency becomes request latency. better-auth/config.ts, emails/nodemailer.ts Medium
15 No error monitoring/alerting integration at all. repo-wide Medium

2. Core principles

P1 — Errors are values with meaning, not strings. Every failure carries a stable machine-readable code, a safe user-facing message, and optional structured context. Clients branch on code, never on message text.

P2 — Catch only what you can handle. A try/catch that just re-throws a generic error is worse than no try/catch at all: it destroys the original code, message, and stack. If you cannot add information or take a recovery action, do not catch. Let it bubble to the layer that owns error translation.

P3 — Errors bubble up; they are translated exactly once, at the boundary. Domain code throws domain errors. The boundary (tRPC middleware, route handler wrapper, error boundary) is the single place that maps them to a transport representation. No TRPCError inside a service function; no NextResponse inside a query helper.

P4 — Never silently swallow. A caught error must be at minimum logged with correlation context. catch {}, catch { return null }, and catch { return undefined } are banned unless accompanied by a comment justifying why the failure is genuinely irrelevant.

P5 — Fail loudly in development, fail safely in production. Development: full stack, full cause chain, full context. Production: a generic message for unexpected errors, the real message for expected ones. Never leak SQL, connection strings, stack traces, or internal IDs to the browser.

P6 — Distinguish expected from unexpected. Expected (NOT_FOUND, CONFLICT, FORBIDDEN, validation) are business outcomes: show them to the user, log at warn or not at all, never alert. Unexpected (DB down, null deref, provider outage) are bugs/incidents: log at error, alert, show a generic message.

P7 — Degrade, don't collapse. A failure in a sidebar widget must not blank the page. Isolate optional data behind boundaries and Suspense so the blast radius matches the importance of the data.

P8 — Every error is traceable. Every unexpected error gets a correlation ID, surfaced to the user ("Reference: a1b2c3") and logged alongside route, user ID, and org. Support conversations start with that ID.


3. The error model

3.1 Error codes

Create src/server/errors/codes.ts. One flat, stable, exhaustive list. Codes are part of your API contract — renaming one is a breaking change.

export const ErrorCode = {
  // ── Auth / identity ──────────────────────────────────────────
  UNAUTHENTICATED: "UNAUTHENTICATED",
  SESSION_EXPIRED: "SESSION_EXPIRED",
  EMAIL_NOT_VERIFIED: "EMAIL_NOT_VERIFIED",
  INVALID_CREDENTIALS: "INVALID_CREDENTIALS",

  // ── Authorization / tenancy ──────────────────────────────────
  FORBIDDEN: "FORBIDDEN",
  NOT_ORG_MEMBER: "NOT_ORG_MEMBER",
  INSUFFICIENT_ROLE: "INSUFFICIENT_ROLE",
  WRONG_TENANT: "WRONG_TENANT",

  // ── Resources ────────────────────────────────────────────────
  ORG_NOT_FOUND: "ORG_NOT_FOUND",
  MEMBER_NOT_FOUND: "MEMBER_NOT_FOUND",
  INVITATION_NOT_FOUND: "INVITATION_NOT_FOUND",
  USER_NOT_FOUND: "USER_NOT_FOUND",

  // ── Conflicts / business rules ───────────────────────────────
  EMAIL_ALREADY_EXISTS: "EMAIL_ALREADY_EXISTS",
  ORG_SLUG_TAKEN: "ORG_SLUG_TAKEN",
  ALREADY_A_MEMBER: "ALREADY_A_MEMBER",
  INVITATION_EXPIRED: "INVITATION_EXPIRED",
  INVITATION_ALREADY_USED: "INVITATION_ALREADY_USED",
  ALREADY_AUTHENTICATED: "ALREADY_AUTHENTICATED",
  SEAT_LIMIT_REACHED: "SEAT_LIMIT_REACHED",

  // ── Input ────────────────────────────────────────────────────
  VALIDATION_FAILED: "VALIDATION_FAILED",
  FILE_TOO_LARGE: "FILE_TOO_LARGE",
  UNSUPPORTED_FILE_TYPE: "UNSUPPORTED_FILE_TYPE",

  // ── Infrastructure / dependencies ────────────────────────────
  DATABASE_ERROR: "DATABASE_ERROR",
  EMAIL_DELIVERY_FAILED: "EMAIL_DELIVERY_FAILED",
  UPLOAD_FAILED: "UPLOAD_FAILED",
  EXTERNAL_SERVICE_ERROR: "EXTERNAL_SERVICE_ERROR",
  RATE_LIMITED: "RATE_LIMITED",

  // ── Fallback ─────────────────────────────────────────────────
  INTERNAL_ERROR: "INTERNAL_ERROR",
} as const;

export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];

3.2 AppError

src/server/errors/app-error.ts. This is the only error class domain code throws.

import { ErrorCode } from "./codes";

type Severity = "warn" | "error" | "fatal";

interface AppErrorOptions {
  /** Message safe to render to an end user. Required — write it for a human. */
  message: string;
  /** Structured, non-sensitive context for logs. Never rendered to users. */
  context?: Record<string, unknown>;
  /** The underlying error, preserved for the log's cause chain. */
  cause?: unknown;
  /**
   * `true`  → a business outcome. Message is shown to the user; not alerted.
   * `false` → a bug or incident. Message is redacted in prod; alerted.
   * Defaults are derived from the code (see EXPECTED_CODES).
   */
  expected?: boolean;
  severity?: Severity;
}

/** Codes that represent normal business outcomes rather than incidents. */
const EXPECTED_CODES = new Set<ErrorCode>([
  ErrorCode.UNAUTHENTICATED,
  ErrorCode.SESSION_EXPIRED,
  ErrorCode.EMAIL_NOT_VERIFIED,
  ErrorCode.INVALID_CREDENTIALS,
  ErrorCode.FORBIDDEN,
  ErrorCode.NOT_ORG_MEMBER,
  ErrorCode.INSUFFICIENT_ROLE,
  ErrorCode.WRONG_TENANT,
  ErrorCode.ORG_NOT_FOUND,
  ErrorCode.MEMBER_NOT_FOUND,
  ErrorCode.INVITATION_NOT_FOUND,
  ErrorCode.USER_NOT_FOUND,
  ErrorCode.EMAIL_ALREADY_EXISTS,
  ErrorCode.ORG_SLUG_TAKEN,
  ErrorCode.ALREADY_A_MEMBER,
  ErrorCode.INVITATION_EXPIRED,
  ErrorCode.INVITATION_ALREADY_USED,
  ErrorCode.ALREADY_AUTHENTICATED,
  ErrorCode.SEAT_LIMIT_REACHED,
  ErrorCode.VALIDATION_FAILED,
  ErrorCode.FILE_TOO_LARGE,
  ErrorCode.UNSUPPORTED_FILE_TYPE,
  ErrorCode.RATE_LIMITED,
]);

export class AppError extends Error {
  readonly code: ErrorCode;
  readonly context?: Record<string, unknown>;
  readonly expected: boolean;
  readonly severity: Severity;

  constructor(code: ErrorCode, opts: AppErrorOptions) {
    super(opts.message, { cause: opts.cause });
    this.name = "AppError";
    this.code = code;
    this.context = opts.context;
    this.expected = opts.expected ?? EXPECTED_CODES.has(code);
    this.severity = opts.severity ?? (this.expected ? "warn" : "error");
    Error.captureStackTrace?.(this, AppError);
  }

  static is(err: unknown): err is AppError {
    return err instanceof AppError;
  }

  /** Wrap an unknown thrown value without losing it. */
  static from(err: unknown, code: ErrorCode, message: string): AppError {
    if (AppError.is(err)) return err;
    return new AppError(code, { message, cause: err });
  }
}

Why a class and not a discriminated-union Result type? Both are defensible. A class wins here because tRPC, Next.js, and React error boundaries are all built on throw/catch, and Error.cause gives you a free chain. Reserve Result-style returns for hot loops where throwing is measurably costly — not the case in this app.

3.3 Convenience constructors

src/server/errors/index.ts — keeps call sites to one line.

export * from "./app-error";
export * from "./codes";

import { AppError } from "./app-error";
import { ErrorCode } from "./codes";

export const errors = {
  orgNotFound: (slug?: string) =>
    new AppError(ErrorCode.ORG_NOT_FOUND, {
      message: "We couldn't find that organization.",
      context: { slug },
    }),

  notOrgMember: (userId: string, orgId: string) =>
    new AppError(ErrorCode.NOT_ORG_MEMBER, {
      message: "You are not a member of this organization.",
      context: { userId, orgId },
    }),

  insufficientRole: (required: string, actual: string) =>
    new AppError(ErrorCode.INSUFFICIENT_ROLE, {
      message: `This action requires the ${required} role.`,
      context: { required, actual },
    }),

  emailAlreadyExists: (email: string) =>
    new AppError(ErrorCode.EMAIL_ALREADY_EXISTS, {
      message: "An account with this email already exists.",
      context: { email },
    }),

  invitationExpired: (invitationId: string) =>
    new AppError(ErrorCode.INVITATION_EXPIRED, {
      message: "This invitation has expired. Ask an admin to send a new one.",
      context: { invitationId },
    }),

  database: (operation: string, cause: unknown) =>
    new AppError(ErrorCode.DATABASE_ERROR, {
      message: "A database error occurred.",
      context: { operation },
      cause,
      expected: false,
    }),
};

3.4 Code → HTTP / tRPC mapping

src/server/errors/mapping.ts. One table, used by both the tRPC boundary and route handlers.

import type { TRPC_ERROR_CODE_KEY } from "@trpc/server/rpc";
import { ErrorCode } from "./codes";

export const CODE_TO_TRPC: Record<ErrorCode, TRPC_ERROR_CODE_KEY> = {
  UNAUTHENTICATED: "UNAUTHORIZED",
  SESSION_EXPIRED: "UNAUTHORIZED",
  EMAIL_NOT_VERIFIED: "FORBIDDEN",
  INVALID_CREDENTIALS: "UNAUTHORIZED",

  FORBIDDEN: "FORBIDDEN",
  NOT_ORG_MEMBER: "FORBIDDEN",
  INSUFFICIENT_ROLE: "FORBIDDEN",
  WRONG_TENANT: "FORBIDDEN",

  ORG_NOT_FOUND: "NOT_FOUND",
  MEMBER_NOT_FOUND: "NOT_FOUND",
  INVITATION_NOT_FOUND: "NOT_FOUND",
  USER_NOT_FOUND: "NOT_FOUND",

  EMAIL_ALREADY_EXISTS: "CONFLICT",
  ORG_SLUG_TAKEN: "CONFLICT",
  ALREADY_A_MEMBER: "CONFLICT",
  INVITATION_EXPIRED: "BAD_REQUEST",
  INVITATION_ALREADY_USED: "CONFLICT",
  ALREADY_AUTHENTICATED: "BAD_REQUEST",
  SEAT_LIMIT_REACHED: "FORBIDDEN",

  VALIDATION_FAILED: "BAD_REQUEST",
  FILE_TOO_LARGE: "PAYLOAD_TOO_LARGE",
  UNSUPPORTED_FILE_TYPE: "UNSUPPORTED_MEDIA_TYPE",

  DATABASE_ERROR: "INTERNAL_SERVER_ERROR",
  EMAIL_DELIVERY_FAILED: "INTERNAL_SERVER_ERROR",
  UPLOAD_FAILED: "INTERNAL_SERVER_ERROR",
  EXTERNAL_SERVICE_ERROR: "BAD_GATEWAY",
  RATE_LIMITED: "TOO_MANY_REQUESTS",

  INTERNAL_ERROR: "INTERNAL_SERVER_ERROR",
};

export const CODE_TO_HTTP: Record<ErrorCode, number> = {
  UNAUTHENTICATED: 401,
  SESSION_EXPIRED: 401,
  EMAIL_NOT_VERIFIED: 403,
  INVALID_CREDENTIALS: 401,
  FORBIDDEN: 403,
  NOT_ORG_MEMBER: 403,
  INSUFFICIENT_ROLE: 403,
  WRONG_TENANT: 403,
  ORG_NOT_FOUND: 404,
  MEMBER_NOT_FOUND: 404,
  INVITATION_NOT_FOUND: 404,
  USER_NOT_FOUND: 404,
  EMAIL_ALREADY_EXISTS: 409,
  ORG_SLUG_TAKEN: 409,
  ALREADY_A_MEMBER: 409,
  INVITATION_EXPIRED: 400,
  INVITATION_ALREADY_USED: 409,
  ALREADY_AUTHENTICATED: 400,
  SEAT_LIMIT_REACHED: 403,
  VALIDATION_FAILED: 400,
  FILE_TOO_LARGE: 413,
  UNSUPPORTED_FILE_TYPE: 415,
  DATABASE_ERROR: 500,
  EMAIL_DELIVERY_FAILED: 500,
  UPLOAD_FAILED: 500,
  EXTERNAL_SERVICE_ERROR: 502,
  RATE_LIMITED: 429,
  INTERNAL_ERROR: 500,
};

4. Layer 1 — Database & data access

Rules

  • DA-1 Data-access helpers throw AppError, never TRPCError. They must stay transport-agnostic.
  • DA-2 Wrap multi-write operations in db.transaction. Any sequence of ≥2 writes that must succeed or fail together is a transaction.
  • DA-3 Translate driver errors (unique violation, FK violation) into domain codes. Never let a raw postgres error reach the client.
  • DA-4 Ban non-null assertions on query results. findFirst returns T | undefined; a ! is a runtime crash waiting for the empty case.

Transactions

createWorkspace (auth.ts:286-320) currently does: insert org → insert member → insert usersToOrganizations → update session. If step 3 fails, you have an organization nobody can reach and a member row pointing at it. Wrap it:

const result = await ctx.db.transaction(async (tx) => {
  const [org] = await tx
    .insert(organization)
    .values({ ...rest, name: companyName, logo: logo ?? "" })
    .returning({ id: organization.id, slug: organization.slug });

  if (!org) {
    throw new AppError(ErrorCode.DATABASE_ERROR, {
      message: "Failed to create workspace.",
      context: { companyName },
    });
  }

  await tx.insert(member).values({
    organizationId: org.id,
    role: yourRole,
    title: jobTitle,
    userId: verifiedUserId,
  });

  await tx.insert(usersToOrganizations).values({
    userId: verifiedUserId,
    organizationId: org.id,
  });

  await tx
    .update(sessionTable)
    .set({ activeOrganizationSlug: org.slug })
    .where(eq(sessionTable.token, ctx.session.session.token));

  return org;
});

Throwing inside the callback rolls back automatically. Note that the in-memory mutation ctx.session.session.activeOrganizationSlug = org.slug must happen after the transaction commits, not inside it.

Translating driver errors

src/server/db/errors.ts:

import { AppError, ErrorCode } from "~/server/errors";

/** postgres-js surfaces PostgreSQL SQLSTATE codes on `err.code`. */
const PG = {
  UNIQUE_VIOLATION: "23505",
  FOREIGN_KEY_VIOLATION: "23503",
  NOT_NULL_VIOLATION: "23502",
  CHECK_VIOLATION: "23514",
  SERIALIZATION_FAILURE: "40001",
  DEADLOCK_DETECTED: "40P01",
} as const;

function pgCode(err: unknown): string | undefined {
  if (typeof err === "object" && err !== null && "code" in err) {
    const c = (err as { code: unknown }).code;
    return typeof c === "string" ? c : undefined;
  }
}

/**
 * Run a DB operation, mapping driver errors to domain errors.
 * `constraints` maps a constraint name to the domain error to throw.
 */
export async function dbOp<T>(
  operation: string,
  fn: () => Promise<T>,
  constraints: Record<string, () => AppError> = {},
): Promise<T> {
  try {
    return await fn();
  } catch (err) {
    if (AppError.is(err)) throw err; // don't re-wrap our own

    const code = pgCode(err);

    if (code === PG.UNIQUE_VIOLATION) {
      const name =
        typeof err === "object" && err !== null && "constraint_name" in err
          ? String((err as { constraint_name: unknown }).constraint_name)
          : undefined;
      const mapped = name ? constraints[name] : undefined;
      if (mapped) throw mapped();
    }

    throw new AppError(ErrorCode.DATABASE_ERROR, {
      message: "A database error occurred.",
      context: { operation, pgCode: code },
      cause: err,
      expected: false,
    });
  }
}

Usage — the unique index on organization.slug becomes a proper ORG_SLUG_TAKEN instead of a 500:

const [org] = await dbOp(
  "organization.insert",
  () => tx.insert(organization).values({ ... }).returning({ ... }),
  { organization_slug_unique: () => errors.orgSlugTaken(slug) },
);

Replace non-null assertions

In org.ts:44-52, members[0]! assumes the filtered relation always has a row. With noUncheckedIndexedAccess: true the compiler is telling you it may not. Filter instead of asserting:

const result = res
  .map((e) => e.organization)
  .flatMap(({ members, ...rest }) => {
    const membership = members[0];
    // A user's org with no membership row is an integrity violation —
    // log it and skip the row rather than crashing the whole query.
    if (!membership) {
      logger.warn("org.membership_missing", { orgId: rest.id, userId });
      return [];
    }
    return [
      {
        ...rest,
        isActive: !membership.lastWorking,
        role: membership.role,
        position: membership.position,
        timePeriod: formatTenure(membership),
      },
    ];
  });

Same applies to ctx.session.session.activeOrganizationSlug! (auth.ts:48) — that field is declared required: false in the better-auth config, so it is genuinely nullable. Check it and throw ErrorCode.WRONG_TENANT if absent.


5. Layer 2 — tRPC procedures (the most important layer)

The single most important rule

TP-1 — Do not wrap a procedure body in try/catch unless you are adding information or recovering.

Today every procedure in auth.ts looks like this:

// ❌ DELETE THIS PATTERN EVERYWHERE
.mutation(async ({ ctx, input }) => {
  try {
    if (!org) throw new TRPCError({ code: "NOT_FOUND", message: "Organization not found!" });
    // ...
  } catch (err) {
    console.log({ err });
    throw new TRPCError({
      message: "Something went wrong while runnig the code.",
      code: "INTERNAL_SERVER_ERROR",
    });
  }
})

This is actively harmful. The NOT_FOUND you carefully threw on line 72 is caught four lines later and destroyed. Every failure — a validation conflict, a missing org, a genuine DB outage — reaches the user as the same misspelled generic string, with a 500 status that tells monitoring "server is broken" when the user simply typed a duplicate email. It also makes the client unable to react: there is no code to branch on.

The correct version — no try/catch at all:

// ✅
.mutation(async ({ ctx, input }) => {
  const org = await getOrgBySlug(ctx.db, ctx.session.session.activeOrganizationSlug);
  if (!org) throw errors.orgNotFound(ctx.session.session.activeOrganizationSlug);

  const membership = await getMembership(ctx.db, ctx.session.user.id, org.id);
  if (!membership) throw errors.notOrgMember(ctx.session.user.id, org.id);

  return inviteCoWorkers({ db: ctx.db, org, membership, invitees: input.invities });
})

Unhandled throws are caught by the tRPC error middleware (§6), which logs them once with full context and maps them to the right code. One catch site, not fifty.

When try/catch is correct in a procedure

Only when you do something with the error:

// ✅ Adding context the boundary cannot know
try {
  await auth.api.signUpEmail({
    body: { name, email, password },
    headers: ctx.headers,
  });
} catch (err) {
  throw AppError.from(
    err,
    ErrorCode.INTERNAL_ERROR,
    "Failed to create your account.",
  );
}

// ✅ Recovering — a failed avatar fetch shouldn't fail signup
let avatarUrl: string | null = null;
try {
  avatarUrl = await fetchAvatar(name);
} catch (err) {
  logger.warn("avatar.fetch_failed", { err }); // degrade, don't fail
}

Rules

  • TP-2 Procedures orchestrate; business logic lives in src/server/services/** and throws AppError. Keep routers thin.
  • TP-3 Authorization failures are thrown by reusable middleware, not re-implemented per procedure (§6.1).
  • TP-4 Validate all input with Zod. .input() is mandatory even for "simple" params — a z.string() beats a hand-rolled check.
  • TP-5 Never return undefined to signal failure. A procedure either returns data or throws. (org.ts currently violates this.)
  • TP-6 Partial-success operations report per-item outcomes rather than throwing. inviteCoWorker already uses Promise.allSettled for emails — but then discards the result. Return it:
type InviteResult =
  | { email: string; status: "sent" }
  | { email: string; status: "skipped"; reason: "already_member" }
  | { email: string; status: "failed"; reason: "email_delivery" };

// The DB rows are committed; email is best-effort. Tell the client which is which
// so the UI can say "3 sent, 1 failed to deliver" instead of a binary success.
return { results, sent: n, failed: m };

This matters: today inviteCoWorker returns bare true even when every single email bounced.


6. Layer 3 — tRPC infrastructure: middleware, formatter, logging

Everything below lives in src/server/api/trpc.ts.

6.1 Auth & tenancy middleware

export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
  if (!ctx.session?.user) {
    throw new AppError(ErrorCode.UNAUTHENTICATED, {
      message: "Please sign in to continue.",
    });
  }
  return next({
    ctx: { session: { ...ctx.session, user: ctx.session.user } },
  });
});

/** Requires an active organization on the session. */
export const orgProcedure = protectedProcedure.use(async ({ ctx, next }) => {
  const slug = ctx.session.session.activeOrganizationSlug;
  if (!slug) {
    throw new AppError(ErrorCode.WRONG_TENANT, {
      message: "No active workspace selected.",
      context: { userId: ctx.session.user.id },
    });
  }

  const org = await ctx.db.query.organization.findFirst({
    where: eq(organization.slug, slug),
    columns: { id: true, name: true, slug: true },
  });
  if (!org) throw errors.orgNotFound(slug);

  const membership = await ctx.db.query.member.findFirst({
    where: and(
      eq(member.userId, ctx.session.user.id),
      eq(member.organizationId, org.id),
    ),
    columns: { id: true, role: true },
  });
  if (!membership) throw errors.notOrgMember(ctx.session.user.id, org.id);

  return next({ ctx: { ...ctx, org, membership } });
});

/** Role gate, composed on top of orgProcedure. */
export const roleProcedure = (...allowed: WORKFORGE_ROLES[]) =>
  orgProcedure.use(({ ctx, next }) => {
    if (!allowed.includes(ctx.membership.role as WORKFORGE_ROLES)) {
      throw errors.insufficientRole(allowed.join(" or "), ctx.membership.role);
    }
    return next();
  });

This removes the duplicated org/member lookups currently copy-pasted into inviteCoWorker, and makes "who may call this" visible in the procedure's signature: roleProcedure("OWNER", "HR").input(...).

6.2 The error-normalizing middleware

This is the single catch site for the whole API.

import { TRPCError } from "@trpc/server";
import { ZodError } from "zod";
import { AppError, ErrorCode } from "~/server/errors";
import { CODE_TO_TRPC } from "~/server/errors/mapping";
import { logger } from "~/server/logger";
import { randomUUID } from "crypto";

const errorMiddleware = t.middleware(async ({ next, path, type, ctx }) => {
  const start = Date.now();
  const result = await next();

  if (!result.ok) {
    // tRPC wraps thrown values in a TRPCError, preserving the original on `cause`.
    const raw = result.error.cause ?? result.error;
    const traceId = randomUUID().slice(0, 8);

    const base = {
      traceId,
      path,
      type,
      durationMs: Date.now() - start,
      userId: ctx.session?.user?.id,
      orgSlug: ctx.session?.session?.activeOrganizationSlug,
    };

    if (raw instanceof ZodError) {
      logger.warn("trpc.validation_failed", { ...base, issues: raw.issues });
      throw new TRPCError({
        code: "BAD_REQUEST",
        message: "Some of the information you entered isn't valid.",
        cause: raw,
      });
    }

    if (AppError.is(raw)) {
      logger[raw.severity === "warn" ? "warn" : "error"]("trpc.app_error", {
        ...base,
        code: raw.code,
        message: raw.message,
        context: raw.context,
        expected: raw.expected,
        cause: raw.cause,
      });
      throw new TRPCError({
        code: CODE_TO_TRPC[raw.code],
        message: raw.message,
        cause: raw,
      });
    }

    // Truly unexpected — this is an incident.
    logger.error("trpc.unhandled", { ...base, err: raw });
    throw new TRPCError({
      code: "INTERNAL_SERVER_ERROR",
      message: `Something went wrong on our end. Reference: ${traceId}`,
      cause: raw,
    });
  }

  return result;
});

// Apply to EVERY procedure by putting it on the base:
const baseProcedure = t.procedure.use(errorMiddleware);
export const publicProcedure = baseProcedure;
// protectedProcedure / orgProcedure build on baseProcedure, so they inherit it.

Ordering matters: errorMiddleware must be the outermost middleware so it also catches throws from the auth and tenancy middlewares.

6.3 errorFormatter — shape the client contract

const t = initTRPC.context<typeof createTRPCContext>().create({
  transformer: superjson,
  errorFormatter({ shape, error }) {
    const app = AppError.is(error.cause) ? error.cause : null;
    const isProd = env.NODE_ENV === "production";
    const isInternal = error.code === "INTERNAL_SERVER_ERROR";

    return {
      ...shape,
      // Never leak internals in production.
      message:
        isProd && isInternal && !app?.expected ? shape.message : shape.message,
      data: {
        ...shape.data,
        // Drop the stack in production — it ships to the browser otherwise.
        stack: isProd ? undefined : shape.data.stack,
        appCode: app?.code ?? ErrorCode.INTERNAL_ERROR,
        expected: app?.expected ?? false,
        zodError:
          error.cause instanceof ZodError ? error.cause.flatten() : null,
      },
    };
  },
});

appCode is what the client branches on. stack removal is not optional — tRPC includes it in shape.data by default and it will be visible in the browser's network tab.

6.4 The HTTP handler's onError

src/app/api/trpc/[trpc]/route.ts currently logs only in development. Invert that — production is exactly where you need it:

const handler = (req: NextRequest) =>
  fetchRequestHandler({
    endpoint: "/api/trpc",
    req,
    router: appRouter,
    createContext: () => createContext(req),
    onError: ({ path, error, type }) => {
      // The middleware already logged with full context; this is the safety net
      // for failures that happen *outside* procedure execution — context
      // creation, body parsing, transformer errors.
      if (!AppError.is(error.cause)) {
        logger.error("trpc.handler_error", {
          path: path ?? "<no-path>",
          type,
          code: error.code,
          message: error.message,
          err: error,
        });
      }
    },
  });

Note createTRPCContext calls auth.api.getSession — if the session store is down, that throws before any middleware runs. onError is the only thing that will see it.


7. Layer 4 — Route handlers (app/api/**)

Rules

  • RH-1 Parse every request body with Zod. await request.json() throws on malformed input; that throw must be caught.
  • RH-2 Return a consistent JSON error envelope.
  • RH-3 Wrap handlers in a shared adapter rather than repeating try/catch.

Error envelope

// src/server/errors/http.ts
export interface ErrorEnvelope {
  error: {
    code: ErrorCode;
    message: string;
    traceId: string;
    details?: unknown;
  };
}

export function errorResponse(
  err: unknown,
  traceId: string,
): NextResponse<ErrorEnvelope> {
  const app = AppError.is(err) ? err : null;
  const code = app?.code ?? ErrorCode.INTERNAL_ERROR;
  const status = CODE_TO_HTTP[code];
  const safeMessage = app?.expected
    ? app.message
    : `Something went wrong. Reference: ${traceId}`;

  return NextResponse.json(
    { error: { code, message: safeMessage, traceId } },
    { status },
  );
}

Handler adapter

// src/server/errors/with-error-handling.ts
export function withErrorHandling<T extends unknown[]>(
  name: string,
  handler: (req: NextRequest, ...args: T) => Promise<Response>,
) {
  return async (req: NextRequest, ...args: T): Promise<Response> => {
    const traceId = randomUUID().slice(0, 8);
    try {
      return await handler(req, ...args);
    } catch (err) {
      const app = AppError.is(err) ? err : null;
      logger[app?.expected ? "warn" : "error"](`route.${name}`, {
        traceId,
        method: req.method,
        url: req.nextUrl.pathname,
        code: app?.code,
        context: app?.context,
        err,
      });
      return errorResponse(err, traceId);
    }
  };
}

Applying it — /api/set-tenant

Currently await request.json() is unguarded and the result is as-cast. Malformed JSON → unhandled rejection → opaque 500.

const setTenantSchema = z.object({
  slug: z
    .string()
    .min(1)
    .max(63)
    .regex(/^[a-z0-9-]+$/),
});

export const POST = withErrorHandling("set-tenant", async (req) => {
  const body = await req.json().catch(() => {
    throw new AppError(ErrorCode.VALIDATION_FAILED, {
      message: "Invalid request body.",
    });
  });

  const parsed = setTenantSchema.safeParse(body);
  if (!parsed.success) {
    throw new AppError(ErrorCode.VALIDATION_FAILED, {
      message: "Invalid workspace identifier.",
      context: { issues: parsed.error.issues },
    });
  }
  // ... set cookie
});

Security note: /api/set-tenant sets the tenant cookie from an unauthenticated request body. Error handling won't fix that — verify the caller is actually a member of slug before setting the cookie. Flagging it here because it surfaces as a confusing "wrong tenant" error class downstream.

Applying it — /api/uploads

The existing handler is the best error handling in the repo (validates presence, type, size; returns 400s). Three improvements:

  1. Fix the field-name mismatch. The route reads formData.get("logo"); useUpload sends "file". Standardize on "file" and update onboard/company/page.tsx, which sends "logo".
  2. Use domain codes so the client can distinguish "too large" from "wrong type" from "upload service down".
  3. Add a timeout to the Cloudinary upload — the promise wrapping upload_stream can hang indefinitely if the network stalls (§13).

8. Layer 5 — Middleware (src/middleware.ts)

Middleware runs on every matched request. An unhandled throw here is a site-wide outage, and it is the one place where "fail open vs. fail closed" is a real decision.

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  if (isPublicPath(pathname)) return NextResponse.next();

  let session: Session | null = null;
  try {
    session = await auth.api.getSession({ headers: request.headers });
  } catch (err) {
    logger.error("middleware.session_failed", { pathname, err });
    // FAIL CLOSED on authenticated routes: we cannot verify identity,
    // so we must not serve tenant content. Send to login rather than 500.
    const loginUrl = new URL(`http://${BASE_DOMAIN}/onboard/login`);
    loginUrl.searchParams.set("error", "session_unavailable");
    return NextResponse.redirect(loginUrl);
  }
  // ... existing routing logic
}

Rules

  • MW-1 Every await in middleware is inside try/catch. There is no boundary above it.
  • MW-2 Fail closed for anything gated by identity; fail open (NextResponse.next()) only for cosmetic concerns like locale detection.
  • MW-3 Never throw to produce a redirect — return the NextResponse.
  • MW-4 Redirect loops are an error class of their own. /onboard/login is in PUBLIC_PATHS, which prevents the obvious loop — keep it that way, and add a redirect counter (e.g. a ?r=n param, bail at 3) if the tenancy rules grow.
  • MW-5 Keep middleware fast and dependency-light. It currently imports better-auth, which pulls in the Drizzle adapter and the DB client on every request; that widens the failure surface considerably. Consider verifying the session cookie signature directly in middleware and doing full session resolution in RSC/tRPC instead.

9. Layer 6 — Server Components & RSC data fetching

The root layout problem

src/app/layout.tsx:29-35:

const [session, dateData, orgDetails] = await Promise.all([
  auth.api.getSession({ headers: await headers() }),
  getDateData(),
  api.organization.getUserOrgDetails(),
]);

Three issues:

  1. Promise.all is all-or-nothing. If getDateData() (which hits Calendarific, an external API) fails, the entire application fails to render — including /pricing, /careers, and every marketing page that doesn't need any of this.
  2. This is the root layout. There is no error.tsx above it. A throw here escapes to global-error.tsx, which also doesn't exist.
  3. It fetches org data for anonymous visitors on public pages, coupling the marketing site's availability to the app's database.

This is almost certainly why org.ts swallows its error and returns undefined — it's a workaround for the crash rather than a fix. Once the boundaries below exist, that swallow must be removed.

Fix: Promise.allSettled + explicit degradation

const [sessionR, dateR, orgR] = await Promise.allSettled([
  auth.api.getSession({ headers: await headers() }),
  getDateData(),
  api.organization.getUserOrgDetails(),
]);

const session = sessionR.status === "fulfilled" ? sessionR.value : null;
if (sessionR.status === "rejected") {
  logger.error("layout.session_failed", { err: sessionR.reason });
}

// Date data is decorative — an empty fallback is fine.
const dateData =
  dateR.status === "fulfilled" ? dateR.value : FALLBACK_DATE_DATA;

// Org details are only meaningful when signed in.
const orgDetails = orgR.status === "fulfilled" ? orgR.value : [];

Better fix: move optional data out of the root layout

Push org fetching down to app/app/[organization]/layout.tsx where it's actually needed, wrap it in <Suspense> with a skeleton (workspace-skeleton.tsx already exists), and let the segment's own error.tsx handle its failures. The root layout should fetch nothing that public pages don't need.

Rules

  • RSC-1 Every page.tsx / layout.tsx that fetches data has an error.tsx in the same segment or an ancestor.
  • RSC-2 Promise.all only when every promise is required. Otherwise Promise.allSettled with explicit fallbacks.
  • RSC-3 Use notFound() for genuinely missing resources — app/[organization]/layout.tsx correctly does this. Pair it with a not-found.tsx in that segment (the root not-found.tsx exists but has no tenant context).
  • RSC-4 Never redirect() inside a try block. redirect() works by throwing NEXT_REDIRECT; a surrounding catch will swallow it and turn a redirect into an error. Same for notFound(). Put them after the try/catch, or re-throw via isRedirectError.
  • RSC-5 Wrap independent, non-critical widgets (current-project, next-holiday, notes, timer) in their own <Suspense> + boundary so one failing widget doesn't blank the dashboard.

10. Layer 7 — React error boundaries (error.tsx)

None of these files exist today. This is the highest-leverage, lowest-effort fix in this document.

Required files

File Catches
src/app/global-error.tsx Errors in the root layout itself. Must render its own <html>/<body>.
src/app/error.tsx Errors anywhere in the public/marketing tree.
src/app/app/[organization]/error.tsx Errors in the authenticated app shell.
src/app/app/[organization]/[feature]/error.tsx Per-feature isolation (projects, team, finance…).
src/app/onboard/error.tsx Onboarding — critical funnel, deserves a tailored recovery path.

Template

// src/app/app/[organization]/error.tsx
"use client";

import { useEffect } from "react";
import { Button } from "~/components/ui/button";

export default function AppError({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    // Client-side reporting. `digest` correlates to the server-side log entry.
    reportError(error, {
      digest: error.digest,
      boundary: "app/[organization]",
    });
  }, [error]);

  return (
    <div className="flex flex-col justify-center items-center gap-4 p-8 min-h-[60vh]">
      <h2 className="font-semibold text-xl">Something went wrong</h2>
      <p className="max-w-md text-muted-foreground text-sm text-center">
        We hit an unexpected problem loading this page. Your data is safe.
      </p>
      {error.digest && (
        <code className="text-muted-foreground text-xs">
          Reference: {error.digest}
        </code>
      )}
      <div className="flex gap-2">
        <Button onClick={reset}>Try again</Button>
        <Button
          variant="secondary"
          onClick={() => (window.location.href = "/app")}
        >
          Back to dashboard
        </Button>
      </div>
    </div>
  );
}

Rules

  • EB-1 error.tsx must be a Client Component ("use client").
  • EB-2 An error.tsx does not catch errors in its own segment's layout.tsx — only in the segment's children. Root-layout errors need global-error.tsx.
  • EB-3 Never render error.message in production. Next.js already redacts server-side messages to a digest, but errors thrown in client components reach the boundary verbatim and may contain internals.
  • EB-4 Always provide a recovery action: reset() plus a safe navigation escape hatch.
  • EB-5 Boundaries do not catch: errors in event handlers, in setTimeout/async callbacks, or during SSR streaming after the shell is sent. Handle those explicitly at the call site.
  • EB-6 Add loading.tsx alongside — a missing loading state makes slow requests look like errors and drives users into retry storms.

11. Layer 8 — Client data layer (TanStack Query + tRPC)

Global defaults

src/trpc/query-client.ts currently sets only staleTime. Add error policy:

import { QueryClient, QueryCache, MutationCache } from "@tanstack/react-query";
import { TRPCClientError } from "@trpc/client";
import { toast } from "sonner";

const NON_RETRYABLE = new Set([
  "BAD_REQUEST",
  "UNAUTHORIZED",
  "FORBIDDEN",
  "NOT_FOUND",
  "CONFLICT",
  "UNPROCESSABLE_CONTENT",
  "PAYLOAD_TOO_LARGE",
  "UNSUPPORTED_MEDIA_TYPE",
]);

function trpcCode(error: unknown): string | undefined {
  return error instanceof TRPCClientError
    ? (error.data as { code?: string } | undefined)?.code
    : undefined;
}

export const createQueryClient = () =>
  new QueryClient({
    queryCache: new QueryCache({
      onError: (error, query) => {
        // Only toast for background refetches of already-rendered data.
        // Initial-load failures are the error boundary's job — toasting there
        // double-reports the same failure.
        if (query.state.data !== undefined) {
          toast.error(userMessage(error));
        }
      },
    }),
    mutationCache: new MutationCache({
      onError: (error, _vars, _ctx, mutation) => {
        // Let a mutation opt out by defining its own onError.
        if (mutation.options.onError) return;
        toast.error(userMessage(error));
      },
    }),
    defaultOptions: {
      queries: {
        staleTime: 30 * 1000,
        retry: (failureCount, error) => {
          const code = trpcCode(error);
          if (code && NON_RETRYABLE.has(code)) return false;
          return failureCount < 2;
        },
        retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 30_000),
        // Opt in per-query; see below.
        throwOnError: false,
      },
      mutations: {
        retry: false, // mutations are not idempotent — never auto-retry
      },
      dehydrate: {
        /* unchanged */
      },
      hydrate: {
        /* unchanged */
      },
    },
  });

Mapping errors to user-facing copy

src/lib/errors/user-message.ts — the client's counterpart to the server taxonomy:

const MESSAGES: Partial<Record<ErrorCode, string>> = {
  UNAUTHENTICATED: "Your session expired. Please sign in again.",
  NOT_ORG_MEMBER: "You don't have access to this workspace.",
  INSUFFICIENT_ROLE: "You don't have permission to do that.",
  EMAIL_ALREADY_EXISTS: "That email is already registered.",
  INVITATION_EXPIRED: "This invitation has expired.",
  RATE_LIMITED: "Too many attempts. Please wait a moment and try again.",
  EMAIL_DELIVERY_FAILED: "We couldn't send the email. Please try again.",
};

export function userMessage(error: unknown): string {
  if (error instanceof TRPCClientError) {
    const data = error.data as
      | { appCode?: ErrorCode; expected?: boolean }
      | undefined;
    if (data?.appCode && MESSAGES[data.appCode]) return MESSAGES[data.appCode]!;
    // The server already wrote a user-safe message for expected errors.
    if (data?.expected && error.message) return error.message;
  }
  if (isNetworkError(error))
    return "Connection lost. Check your internet and try again.";
  return "Something went wrong. Please try again.";
}

Handling UNAUTHORIZED globally

Session expiry currently produces a generic toast on every open query at once. Handle it once:

onError: (error) => {
  if (trpcCode(error) === "UNAUTHORIZED") {
    // Deduplicate — many in-flight queries will fail simultaneously.
    if (!redirectingToLogin) {
      redirectingToLogin = true;
      toast.error("Your session expired. Redirecting to sign in…");
      window.location.href = "/onboard/login";
    }
    return;
  }
  // ...
};

throwOnError — routing errors to boundaries

For a query whose data the page cannot render without, opt into the error boundary rather than handling inline:

const { data } = api.organization.getUserOrgDetails.useQuery(undefined, {
  throwOnError: true, // → nearest error.tsx
});

Rules

  • CQ-1 Never leave a mutation's error unhandled. Either rely on the global MutationCache.onError toast or supply a specific onError. The current try/catch { setStatus("error") } in team/invite.tsx and onboard/company/page.tsx shows the user nothing.
  • CQ-2 Never retry mutations automatically.
  • CQ-3 Distinguish "no data" from "failed to load" in the UI. An empty table and a broken table must look different.
  • CQ-4 Remove console.log({ res }) debug statements from submit handlers (team/invite.tsx:47,50, company/page.tsx:129) — they leak invitee emails and user data into the browser console.

12. Layer 9 — Forms & user-facing feedback

TanStack Form + Zod is already in use. Standardize the server-error path.

Field-level vs. form-level errors

A CONFLICT on email should attach to the email field, not float in a toast:

onSubmit: async ({ value, formApi }) => {
  try {
    await signUp.mutateAsync(value);
  } catch (err) {
    const code = trpcCode(err);

    if (code === "CONFLICT") {
      formApi.setFieldMeta("email", (m) => ({
        ...m,
        errorMap: { onServer: "That email is already registered." },
      }));
      return;
    }

    // Zod errors from the server → map onto the matching fields.
    const zodError = (err as TRPCClientError<AppRouter>).data?.zodError;
    if (zodError) {
      for (const [field, messages] of Object.entries(zodError.fieldErrors)) {
        formApi.setFieldMeta(field, (m) => ({
          ...m,
          errorMap: { onServer: messages?.[0] },
        }));
      }
      return;
    }

    toast.error(userMessage(err));
  }
};

Rules

  • FM-1 Validation errors belong next to the field. Toasts are for form-wide or transport failures.
  • FM-2 Disable submit while isSubmitting — already done in login/page.tsx, missing in others. Double-submits create duplicate invitations and duplicate orgs.
  • FM-3 Never clear a form on error. The user's input is precious; re-entry after a failed submit is a top churn driver in onboarding.
  • FM-4 Multi-step flows (onboard/company/page.tsx) must not advance on failure. Currently nextStep(value) runs after an upload that may have silently failed — logoUpload.status === 200 is checked, but a non-200 falls through to nextStep() anyway with no logo and no message.
  • FM-5 Toast copy: say what happened and what to do. "Something went wrong while runnig the code." fails on both counts (and is misspelled — it's user-visible today).
  • FM-6 Use toast.promise() for long operations so pending/success/error are handled in one place.

13. Layer 10 — External services (email, Cloudinary, third-party APIs)

Every network call to a third party will fail eventually. Treat each as unreliable by default.

Rules

  • EX-1 Every external call has an explicit timeout. Without one, a hung provider connection holds a serverless invocation until the platform kills it.
  • EX-2 Retry only idempotent operations, with exponential backoff and jitter, capped at 2–3 attempts.
  • EX-3 Non-critical side effects must never fail the primary operation. If the welcome email fails, the account was still created — say so.
  • EX-4 Prefer queuing over inline sending for bulk work. inviteCoWorker sends N emails inline; with 50 invitees that's a guaranteed timeout.
  • EX-5 Log provider errors with the provider's own error ID for support escalation.

A reusable wrapper

// src/server/lib/resilient.ts
export async function callExternal<T>(
  service: string,
  fn: (signal: AbortSignal) => Promise<T>,
  opts: { timeoutMs?: number; retries?: number } = {},
): Promise<T> {
  const { timeoutMs = 10_000, retries = 0 } = opts;

  for (let attempt = 0; attempt <= retries; attempt++) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), timeoutMs);
    try {
      return await fn(controller.signal);
    } catch (err) {
      const isLast = attempt === retries;
      logger.warn("external.attempt_failed", { service, attempt, isLast, err });
      if (isLast) {
        throw new AppError(ErrorCode.EXTERNAL_SERVICE_ERROR, {
          message: `${service} is temporarily unavailable.`,
          context: { service, attempts: attempt + 1 },
          cause: err,
          expected: false,
        });
      }
      await sleep(Math.min(2 ** attempt * 250, 4000) + Math.random() * 250);
    } finally {
      clearTimeout(timer);
    }
  }
  throw new Error("unreachable");
}

Email specifically

better-auth/config.ts calls resend.emails.send(...) unguarded inside sendVerificationOTP and sendMagicLink. If Resend is down, sign-up throws from deep inside better-auth with a provider-shaped error the user will never understand.

async sendVerificationOTP({ email, otp, type }) {
  const result = await resend.emails.send({ /* ... */ });

  if (result.error) {
    logger.error("email.otp_failed", {
      email, type, provider: "resend",
      providerError: result.error,
    });
    throw new AppError(ErrorCode.EMAIL_DELIVERY_FAILED, {
      message: "We couldn't send your verification code. Please try again.",
      context: { type },
    });
  }
}

Note: the Resend SDK returns { data, error } rather than throwing — an unchecked call silently succeeds while sending nothing. Check result.error every time.

Also worth resolving: the codebase has two email transports — Resend (better-auth/config.ts) and Gmail/nodemailer (emails/nodemailer.ts, used by inviteCoWorker). Two providers means two failure modes, two sets of credentials, and two deliverability reputations. Consolidate on one, and note that Gmail SMTP has hard daily send limits that will surface as delivery failures under load.


14. Logging & observability

A minimal structured logger

src/server/logger.ts. No dependency required to start.

type Level = "debug" | "info" | "warn" | "error";

interface LogFields {
  traceId?: string;
  userId?: string;
  orgSlug?: string;
  err?: unknown;
  [key: string]: unknown;
}

function serializeError(err: unknown): unknown {
  if (err instanceof Error) {
    return {
      name: err.name,
      message: err.message,
      stack: env.NODE_ENV === "production" ? undefined : err.stack,
      ...(AppError.is(err) && { code: err.code, context: err.context }),
      cause: err.cause ? serializeError(err.cause) : undefined,
    };
  }
  return err;
}

/** Keys whose values must never reach logs. */
const REDACT = new Set([
  "password",
  "token",
  "secret",
  "otp",
  "apiKey",
  "authorization",
  "cookie",
  "sessionToken",
]);

function redact(obj: Record<string, unknown>): Record<string, unknown> {
  return Object.fromEntries(
    Object.entries(obj).map(([k, v]) => [
      k,
      REDACT.has(k)
        ? "[REDACTED]"
        : v && typeof v === "object" && !Array.isArray(v)
          ? redact(v as Record<string, unknown>)
          : v,
    ]),
  );
}

function log(level: Level, event: string, fields: LogFields = {}) {
  const { err, ...rest } = fields;
  const entry = {
    level,
    event,
    timestamp: new Date().toISOString(),
    ...redact(rest),
    ...(err !== undefined && { error: serializeError(err) }),
  };

  if (env.NODE_ENV === "development") {
    console[level === "debug" ? "log" : level](event, entry);
  } else {
    // One JSON object per line — parseable by every log aggregator.
    console[level === "error" ? "error" : "log"](JSON.stringify(entry));
  }
}

export const logger = {
  debug: (e: string, f?: LogFields) => log("debug", e, f),
  info: (e: string, f?: LogFields) => log("info", e, f),
  warn: (e: string, f?: LogFields) => log("warn", e, f),
  error: (e: string, f?: LogFields) => log("error", e, f),
};

Rules

  • LG-1 console.log for errors is banned. All 22 current sites migrate to logger.*. Add an ESLint rule: "no-console": ["error", { allow: [] }] for src/server/**.
  • LG-2 Log once, at the boundary. Logging at every level of the call stack produces N entries per incident and makes rate-based alerting meaningless.
  • LG-3 Event names are stable, dotted, machine-readable identifiers (invite.email_failed), not sentences. You will group and alert on these.
  • LG-4 Never log secrets, passwords, OTPs, session tokens, or full request bodies. console.log({ invitations }) in auth.ts:124 dumps every invitee's email — remove it.
  • LG-5 Every log line carries traceId, plus userId/orgSlug where available.
  • LG-6 Expected errors → warn. Unexpected → error. Only error should page anyone.

Monitoring

Add Sentry (@sentry/nextjs) — it covers RSC, route handlers, middleware, and client boundaries in one install, which matters given how many boundaries this app has. Configure:

  • beforeSend: drop AppErrors where expected === true (they are business outcomes, not incidents — otherwise you drown in "wrong password" alerts).
  • tracesSampleRate: 0.1 in production.
  • Scrub PII: emails and org slugs are tenant-identifying.
  • Set user context from the session and tag by orgSlug so you can see whether an incident is one tenant or all of them.

Alert on: unexpected-error rate > 1% of requests over 5 min; any DATABASE_ERROR; EMAIL_DELIVERY_FAILED rate > 5%; middleware session failures > 0; p99 latency regressions on /api/trpc.

Health checks

Add GET /api/health returning DB connectivity, and GET /api/health/deep checking Resend/Cloudinary reachability. Point uptime monitoring at the shallow one.


15. Anti-patterns found in this codebase

Each entry: what it is, where, why it's wrong, what to do.


AP-1 — Catch-and-rethrow-generic src/server/api/routers/auth.ts — inviteCoWorker:159, getInviteInformation:209, signUpAndSendOTP:262, createWorkspace:325

Every deliberate TRPCError thrown inside the try is caught and replaced with INTERNAL_SERVER_ERROR: "Something went wrong while runnig the code." The NOT_FOUND on line 72, the CONFLICT on line 236, the BAD_REQUEST on line 202 — all unreachable by the client. Users see one misspelled generic message for every failure; monitoring sees 500s for ordinary validation outcomes.

→ Delete all four try/catch blocks. Throw AppError. Let the middleware in §6.2 translate. If you fix one thing in this document, fix this.


AP-2 — Catch that returns undefined src/server/api/routers/org.ts:55-58

} catch (err) {
  console.log({ err });
  console.log("error");
}

The procedure returns undefined on failure, so the client's isError is false and isSuccess is true with no data. The inferred return type becomes T[] | undefined, silently pushing optionality into every consumer. The root layout then passes this undefined into RootContext.

→ Remove the catch entirely.


AP-3 — No error boundaries anywhere src/app/** — zero error.tsx, zero global-error.tsx, zero loading.tsx

→ §10. Start with global-error.tsx and app/app/[organization]/error.tsx.


AP-4 — Production errors are invisible src/app/api/trpc/[trpc]/route.ts:19-27 — onError is undefined unless NODE_ENV === "development"

→ §6.4. Log always; vary verbosity, not existence.


AP-5 — Root layout is a single point of failure src/app/layout.tsx:29-35

→ §9.


AP-6 — Unguarded middleware src/middleware.ts:38

→ §8.


AP-7 — Non-transactional multi-write src/server/api/routers/auth.ts:286-320

→ §4.


AP-8 — Non-null assertions on nullable values org.ts:48,49,50 (members[0]!), auth.ts:48 (activeOrganizationSlug!), auth.ts:152 (invitations[index]!), team/invite.tsx:35 (activeOrganizationSlug!), onboard/company/page.tsx:139 (email.split("@")[1]), company/page.tsx:69 ([step - 1]!)

noUncheckedIndexedAccess: true is enabled precisely to catch these; each ! overrides a correct compiler warning. email.split("@")[1] on a malformed email yields undefined, which flows into emailDomain and renders "undefined.com".

→ Narrow with a check, or ?? fallback. A ! in this codebase requires a comment proving non-nullness.


AP-9 — Debug logging of PII auth.ts:124 (console.log({ invitations }) — all invitee emails), team/invite.tsx:47,50, company/page.tsx:129

→ Delete. See LG-4.


AP-10 — Client mutation failures are invisible team/invite.tsx:53-56, onboard/company/page.tsx:159-162

catch (err) { console.error(err); setStatus("error"); }

Unless the child component renders something distinct for status === "error", the user clicks "Invite" and nothing happens.

→ §11, CQ-1.


AP-11 — Upload field-name mismatch api/uploads/route.ts:15 reads "logo"; hooks/use-upload.ts:29 sends "file"

Any caller using the useUpload hook gets a 400 "No file provided". (onboard/company/page.tsx:143 bypasses the hook and posts "logo" directly, which is why uploads appear to work.)

→ Standardize on "file", update both callers, delete the duplicated axios call in company/page.tsx in favor of the hook.


AP-12 — Unvalidated request bodies api/set-tenant/route.ts:8 — (await request.json()) as { slug?: string }

→ §7, RH-1.


AP-13 — Unchecked SDK result objects better-auth/config.ts:139,168 — await resend.emails.send(...) with the return value discarded

Resend returns { data, error }; it does not throw on API errors. Discarding it means email failures are completely silent.

→ §13.


AP-14 — Promise.allSettled results computed then discarded auth.ts:126-156

The results are inspected and logged (good), but the procedure still returns bare true. The caller cannot tell 10-sent from 0-sent.

→ §5, TP-6.


AP-15 — Empty catch in cleanup paths stores/slices/timer.slice.ts

→ Any intentionally-ignored error needs a comment stating why.


AP-16 — getInviteInformation returns the full invitation row auth.ts:208

return inviteResponse ships every column — inviterId, organizationId, internal timestamps — to an unauthenticated caller (it's a publicProcedure). Not strictly an error-handling bug, but it's the same class of mistake: unbounded data crossing a trust boundary.

→ Select explicit columns.


16. Adoption plan

Sequenced so each phase is independently shippable and the highest-risk gaps close first.

Phase 1 — Stop the bleeding (½ day)

  1. src/app/global-error.tsx + src/app/error.tsx + src/app/app/[organization]/error.tsx
  2. Fix onError in the tRPC route handler to log in production
  3. Delete the four try/catch blocks in auth.ts (AP-1) — the TRPCErrors they were hiding are already correct and will start working immediately
  4. Delete the catch in org.ts (AP-2)
  5. Wrap middleware.ts's getSession in try/catch
  6. Remove PII console.logs (AP-9)

Steps 3–4 will surface previously-hidden failures. Do them after steps 1–2 so you can see and contain what emerges.

Phase 2 — Foundations (1–2 days)

  1. src/server/errors/** — codes, AppError, mapping, convenience constructors
  2. src/server/logger.ts + ESLint no-console for src/server/**
  3. errorMiddleware + errorFormatter in trpc.ts
  4. Migrate auth.ts and org.ts to throw AppError

Phase 3 — Client resilience (1 day)

  1. QueryCache/MutationCache global handlers + retry policy
  2. userMessage() mapping + global UNAUTHORIZED redirect
  3. Fix the mutation handlers in team/invite.tsx and onboard/company/page.tsx
  4. Per-segment error.tsx + loading.tsx for each app feature

Phase 4 — Hardening (1–2 days)

  1. orgProcedure / roleProcedure; remove duplicated auth checks
  2. Transaction for createWorkspace; dbOp for constraint mapping
  3. withErrorHandling + Zod on all route handlers; fix the upload field name
  4. callExternal for Resend/Cloudinary/Calendarific; check result.error
  5. Eliminate non-null assertions (AP-8)

Phase 5 — Observability (½ day)

  1. Sentry with beforeSend filtering of expected errors
  2. /api/health; alerting rules
  3. Structured logs shipped to an aggregator

17. PR review checklist

Copy into .github/pull_request_template.md.

Server

  • No try/catch that only re-throws a generic error
  • No catch that returns null/undefined to signal failure
  • Domain code throws AppError, not TRPCError or NextResponse
  • Every new error uses an existing ErrorCode (or adds one to the enum + both mappings)
  • User-facing messages say what happened and what to do next; no internals leaked
  • Multi-write operations are wrapped in a transaction
  • All input validated with Zod; no as casts on request bodies
  • External calls have a timeout; SDK { error } results are checked
  • Non-critical side effects cannot fail the primary operation
  • logger.* used, never console.*; no secrets or PII in log fields
  • Logged once, at the boundary
  • No ! non-null assertion without a comment justifying it

Client

  • Every mutation has error feedback (global toast or specific onError)
  • Loading, empty, and error states are visually distinct
  • Validation errors render on the field, not only as a toast
  • Submit buttons disable while pending
  • Forms retain user input on failure
  • New route segments have error.tsx and loading.tsx
  • No console.log of response payloads

General

  • Failure paths were manually exercised (kill the DB, force a 500, throttle the network)
  • The error is actionable for the user, or clearly labeled as ours with a reference ID

Appendix A — Quick reference

Situation Do this
Resource missing in a procedure throw errors.orgNotFound(slug)
User lacks permission Use roleProcedure("OWNER"), don't check inline
Business-rule violation throw new AppError(ErrorCode.X, { message: "…" })
Unexpected failure in a procedure Don't catch — let it bubble
Adding context to a caught error throw AppError.from(err, code, message)
Optional data failed logger.warn(...) + fall back; don't throw
Route handler Wrap in withErrorHandling, throw AppError
Middleware try/catch + redirect; never throw
RSC required data Let it throw → error.tsx
RSC optional data Promise.allSettled + fallback
Missing page resource notFound() (outside any try)
Client mutation Global toast, or onError for field-level handling
Client query, data required throwOnError: true
Client query, data optional Handle isError inline

Appendix B — Files to create

src/server/errors/
  ├── codes.ts                  # ErrorCode enum
  ├── app-error.ts              # AppError class
  ├── mapping.ts                # CODE_TO_TRPC, CODE_TO_HTTP
  ├── http.ts                   # errorResponse envelope
  ├── with-error-handling.ts    # route handler adapter
  └── index.ts                  # re-exports + errors.* constructors
src/server/logger.ts
src/server/lib/resilient.ts     # callExternal
src/server/db/errors.ts         # dbOp, PG constraint mapping
src/lib/errors/user-message.ts  # client-side code → copy

src/app/global-error.tsx
src/app/error.tsx
src/app/onboard/error.tsx
src/app/app/[organization]/error.tsx
src/app/app/[organization]/loading.tsx
src/app/app/[organization]/not-found.tsx
src/app/api/health/route.ts