Files
supabase/apps/studio/lib/error-reporting.ts
T
Charis 3a76beea91 feat(studio): classify fetch-layer errors with endpoint and method (#53048)
## Problem

Follow-up to #52730. Resolves part of FE-4772.

Fetch failures and aborts were classified as `UnexpectedError`, and HTTP
error responses with empty, HTML, or plain-text bodies did too.

## Solution

**Network failures and aborts keep their classification.**
`fetchHandler` used to rewrite `Failed to fetch` into a plain `Error`,
so openapi-fetch network failures were classified as `UnexpectedError`.
It now throws `classifyError(err, { endpoint, method })`, giving
`NetworkUnreachable` (same user-facing message, original error as
`cause`) or `RequestAborted`. The endpoint comes from `schemaPath`,
recorded in `onRequest`.

Tagged aborts are no longer named `AbortError`, so `isRequestAborted()`
checks for both. `state/storage-explorer.tsx` uses it, so cancelling a
folder load no longer shows an error toast.

**One place reads error responses.** `readResponseError` in
`data/error-classification.ts` turns an HTTP error response into a
`RawResponseError`. It reads the status, `Retry-After`, the message from
a JSON body or a short `text/plain` body (never HTML), plus `requestId`,
`endpoint`, and `method`. The openapi-fetch middleware serializes its
result into the error body. openapi-fetch builds `error` only from the
response body, so that step can't be skipped. `parseResponseErrorBody`
now only checks the shape. Empty, HTML, and plain-text error bodies now
classify by status. Before, they became `UnexpectedError`.

`fetchGet`/`fetchPost`/`fetchHeadWithTimeout` (Studio's own `/api`
routes) use the same helper. This also fixes a non-JSON error body
making them reject with a `SyntaxError`.

**`requestPathname` is replaced by `endpoint`.** The no-retry list and
the statement-timeout check in `query-client.ts` match OpenAPI patterns
exactly. Critical error messages in `lib/error-reporting.ts` use the
pattern, so concrete project refs stay out of them. `path-to-regexp` is
no longer used, so it's removed.

## Review instructions

1. From `apps/studio`, run `vitest run data lib
components/interfaces/ErrorHandling state`. Expect 4,034 passing tests.
2. Review `readResponseError` in `data/error-classification.ts` and its
use in `data/fetchers.ts`.

## Additional context

### Notes

- Critical error messages now read `endpoint … w/ message: …`. This
regroups those Sentry issues.
- A JSON body's `error` string is now accepted as a message for API
responses. Before, only the `/api` route path read it.

### Testing

- New `data/fetchers-errors.test.ts` covers network failure, abort,
empty/HTML/plain-text/JSON error bodies, service derivation, and `/api`
route non-JSON bodies.
- Unit tests for `readResponseError`, `isRequestAborted`, and the
no-retry endpoint set.
- `vitest run data lib components/interfaces/ErrorHandling state`: 4,034
pass.

## Checklist

Check all before review:

- [ ] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [ ] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
2026-11-09 14:54:04 -05:00

119 lines
3.4 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, endpoint } = error
if (!endpoint || !code) {
captureMessage({
message: `Response Error (no code or endpoint) w/ message: ${error.message}`,
context,
})
return
}
if (code >= 500) {
// Only capture 5XX errors as critical errors
captureMessage({
context,
message: `endpoint ${endpoint} 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)
})
}