Files
supabase/apps/studio/lib/error-reporting.ts
T
Charis b3dd6612d7 feat(studio): classify errors with fault, reason, and per-tag Sentry sampling (#52730)
Follows #52707 (rename `ResponseError` to `StudioError`).

Resolves FE-4772.

## What

Introduces the error core for Studio error classification.

- **Tagged errors.** `lib/errors/studio-errors.ts` defines
`Data.TaggedError` classes (`RequestAborted`, `NetworkUnreachable`,
`MalformedResponse`, `PlatformError`, `UnclassifiedApiError`,
`DbConnectionTimeout`, `UnexpectedError`). Each carries `fault`,
`reason`, `classifiedBy` (`rule` or `default`), `retryable`, and
`service`. `StudioError` is the union type; use `isStudioError` instead
of `instanceof`.
- **Two classifiers** in `data/error-classification.ts`:
- `classifyResponseError` is only for errors from an API response: known
message patterns first, then defaults by status (5xx `PlatformError`,
4xx `UnclassifiedApiError`, no status `UnexpectedError`).
- `classifyError` is for everything else: aborts, browser fetch failures
(matched by message, so ordinary `TypeError` bugs stay
`UnexpectedError`), and unexpected errors.
- `handleError` picks between them, reports, and rethrows the same
instance so React Query receives the classified error.
- **Routing and sampling.** `lib/errors/error-routing.ts` maps every tag
to a Sentry sample rate (`SAMPLE_NEVER`, `SAMPLE_OTHER`, `SAMPLE_OWNED`,
`SAMPLE_ALWAYS`). `reportStudioError` tags events with `sample_rate`,
and `beforeSend` applies it. `alwaysCapture` reports at rate 1. The
global Sentry error `sampleRate` stays unset so the rates don't
multiply.
- **Network failures.** A fetch failure is a `user` fault with reason
`offline` when the browser reports being offline, and a `platform` fault
otherwise.
- **Hand-built errors.** Call sites that wrapped caught exceptions or
made up status codes now use `classifyError` or a specific class instead
of `classifyResponseError`.

## Behavior changes

- Errors that previously went unreported, including unexpected errors
with a message, are now reported to Sentry at their routed sample rate.
- `handleError` no longer logs the stack with `console.error`.
- `MalformedResponse` is defined but not produced yet; a follow-up adds
the empty-body check.

## Testing

- Unit tests for classification, routing, reporting, and the
`beforeSend` sampling helper.
- `pnpm vitest run data lib components/interfaces/ErrorHandling`,
typecheck, lint ratchet, and knip pass locally.
2026-11-04 13:19:01 -05:00

119 lines
3.5 KiB
TypeScript

import * as Sentry from '@sentry/nextjs'
import type { StudioError } from '@/lib/errors/studio-errors'
import { isStudioError } from '@/lib/errors/studio-errors'
type CaptureMessageOptions = {
context: string
message: string
}
const WHITELIST_ERRORS = [
// Common validation errors
'email must be an email',
'Password is known to be weak and easy to guess, please choose a different one',
// Authentication errors
'A user with this email already exists',
'Password should contain at least one character of each',
'You attempted to send email to an inactive recipient',
'New password should be different from the old password',
'Invalid TOTP code entered',
'No SSO provider assigned for this domain',
// Project creation errors
'The following organization members have reached their maximum limits for the number of active free projects',
'db_pass must be longer than or equal to 4 characters',
'There are overdue invoices in the organization(s)',
'name should not contain a . string',
'Project creation in the Supabase dashboard is disabled for this Vercel-managed organization.',
'Your account, which is handled by the Fly Supabase extension, cannot access this endpoint.',
'already exists in your organization.',
]
/**
* Captures a critical error to Sentry, filtering out whitelisted errors.
*
* @param error - The error object (StudioError, Error, or any object with a message property)
* @param context - The context/action that failed (e.g., 'reset password', 'sign up', 'create project')
* Attached as the `context` tag on the Sentry event.
*/
export function captureCriticalError(
error: StudioError | Error | { message: string },
context: string
): void {
if (!error.message) {
return
}
if (isStudioError(error)) {
handleResponseError(error, context)
return
}
if (error instanceof Error) {
handleError(error, context)
return
}
handleUnknownAPIResponseError(error, context)
}
function handleResponseError(error: StudioError, context: string) {
const { code, message, requestPathname } = error
if (!requestPathname || !code) {
captureMessage({
message: `Response Error (no code or requestPathname) w/ message: ${error.message}`,
context,
})
return
}
if (code >= 500) {
// Only capture 5XX errors as critical errors
captureMessage({
context,
message: `requestPathname ${requestPathname} w/ message: ${message}`,
})
return
}
}
function handleError(error: Error, context: string) {
if (!error.message) {
return
}
captureMessage({
message: error.message,
context,
})
}
function handleUnknownAPIResponseError(error: unknown, context: string) {
if (
error &&
typeof error === 'object' &&
'message' in error &&
typeof error.message === 'string'
) {
captureMessage({
message: error.message,
context,
})
}
}
function captureMessage({ message, context }: CaptureMessageOptions) {
if (WHITELIST_ERRORS.some((whitelisted) => message.includes(whitelisted))) {
return
}
// Use captureException (vs captureMessage) so these appear as exceptions in Sentry
// and can have dedicated alert rules. Grouping is still by message since all
// CriticalErrors share the same synthetic stack trace.
Sentry.withScope((scope) => {
scope.setTag('critical', 'true')
scope.setTag('context', context)
const error = new Error(message)
error.name = `CriticalError`
Sentry.captureException(error)
})
}