studio-error-handling

Шаблон отображения ошибок и устранения неполадок для Supabase Studio. Используйте, когда

npx skills add https://github.com/supabase/supabase --skill studio-error-handling

Studio Error Handling Pattern

Full architecture, SQLSTATE predicates, and mapping walkthrough: apps/studio/components/interfaces/ErrorHandling/README.md

How it works

handleError() → throws tagged StudioError → React Query catches → ErrorMatcher / AlertError renders UI
  • Tagged errors: handleError (@/data/fetchers) throws Effect Data.TaggedError instances (_tag, fault: user | platform | third_party | studio, reason, classifiedBy: rule | default, retryable, service, plus legacy message, code, requestId, …). Check with isStudioError(e) from @/lib/errors/studio-errors, never instanceof; StudioError is a union type only.
  • API vs non-API classifiers (data/error-classification.ts): classifyResponseError({ message, code }) is for HTTP API responses only (ERROR_PATTERNS win, else 5xx PlatformError, 4xx UnclassifiedApiError, no status UnexpectedError — never pass a made-up status). classifyError(e) handles everything else (tagged passes through, AbortError → RequestAborted, browser fetch failure → NetworkUnreachable, else UnexpectedError). Successful JSON GETs still empty after recovery reject from the fetch layer as MalformedResponseError (normalizeEmptyBodyResponse) without hitting handleError (reportQueryError still reports it).
  • SQL errors: executeSql runs pg-meta errors through classifySqlResponseError: user/AI SQL becomes UserSqlError (never sent to Sentry); Studio SQL becomes StudioSqlError (redacted message, static queryName required; marked fault: 'user', reason: 'user_input' when isUserFaultSqlState accepts the SQLSTATE via composable isUserFaultForValues (typed values: filters, row edits) or isUserFaultForSql (embedded SQL: policies, functions) in data/error-classification.ts).
  • Privacy & Sentry sampling: the class decides privacy (UserSqlError never sent, StudioSqlError redacted), while ERROR_ROUTING (lib/errors/error-routing.ts) maps every tag + fault to { sentrySampleRate } (SAMPLE_NEVER / SAMPLE_USER_FAULT / SAMPLE_OTHER / SAMPLE_OWNED / SAMPLE_ALWAYS, looked up via getErrorRouting). reportStudioError tags sample_rate (enforced in beforeSend) and sets errorEventId.
  • Reporting timing: QueryCache/MutationCache onError (reportQueryError) reports once after the final retry using sentryContext and alwaysCapture remembered by handleError. Pass reportImmediately: true to handleError only for callers outside React Query.

Key files

FilePurpose
apps/studio/data/error-patterns.tsERROR_PATTERN_MAP (Map<ErrorConstructor, RegExp>) — regex lives here, never in UI components
apps/studio/lib/errors/studio-errors.tsTagged error classes, StudioError union type, isStudioError
apps/studio/data/error-classification.tsclassifyResponseError, classifyError, classifySqlResponseError, predicates
apps/studio/lib/errors/error-routing.tsERROR_ROUTING table per tag and fault, getErrorRouting
apps/studio/components/interfaces/ErrorHandling/ErrorMatcher.tsxLooks up error class in error-mappings.tsx and renders troubleshooting UI
apps/studio/components/interfaces/ErrorHandling/error-mappings.tsxMap<ErrorConstructor, ErrorMapping> ({ id, Troubleshooting })
apps/studio/components/interfaces/ErrorHandling/errorMappings/ConnectionTimeout.tsxReference troubleshooting component (including AI Assistant debug button wiring)
apps/studio/components/interfaces/ErrorHandling/TroubleshootingSections.tsxReusable accordion section components
apps/studio/components/interfaces/ErrorHandling/TroubleshootingAccordion.tsxAccordion wrapper with telemetry

Which component

SituationUse
Query failed and page/section cannot render its data (default across Studio)AlertError from @/components/ui/AlertError
Error may be a classified class with troubleshooting steps (e.g. timeout)ErrorMatcher from @/components/interfaces/ErrorHandling/ErrorMatcher — pass fallback for unclassified errors
Mutation failedThe mutation hook's default onError toast (toast.error from sonner) — don't render an alert (see studio-queries)

AlertError (default)

if (isError) return <AlertError error={error} subject="Failed to retrieve invoices" />
  • Phrase subject as Failed to <verb> <thing> and pass projectRef in project context to pre-fill the support link. 503 responses are reworded automatically.
  • For StudioErrors, getErrorPresentation (AlertError.utils.ts) applies tag/fault defaults (caller props win): displays requestId, errorEventId ("before sampling"), and Copy details (formatErrorDetails strips formattedError, metadata, cause, SQL, and SQL error messages). fault: 'user' hides support/IDs/copy; offline NetworkUnreachable shows a dedicated offline message.
  • Use additionalActions for retry/navigation; use hideContactSupport only when support cannot help on a non-user fault. Prefer early return for primary data and inline {isError && <AlertError … />} for secondary panels.
  • System-fault assumption: AlertError's default copy for plain or non-user-fault errors (including unclassified 4xxs) tells users to refresh/contact support — don't use it blindly for mutation or client-side user-input errors; use the mutation's onError toast or actionable inline copy instead.
  • Never collapse errors into empty states: check isError before rendering empty states, and distinguish unparseable/dropped records from genuinely empty responses.
  • Multi-query views: consolidate errors into a single AlertError rather than sprawling multiple banners, and hide dependent sub-sections whose prerequisite query failed.

ErrorMatcher (classified errors)

Reach for ErrorMatcher when adding dedicated troubleshooting steps for a classified error class (not as a general replacement for AlertError). Pass the full error object from React Query, never error.message:

{
  isError && (
    <ErrorMatcher title="Failed to load tables" error={error} supportFormParams={{ projectRef }} />
  )
}

What NOT to do

  • Do not pass error.message to ErrorMatcher, put regex in error-mappings.tsx, or use Object.assign to stamp _tag (add a tagged class + pattern in data/error-patterns.ts).
  • Do not pass a raw support URL (use supportFormParams={{ projectRef }}), put page titles inside error mappings, or add callback props (onDebugWithAI, onRestartProject) to troubleshooting components (use hooks inside them).
  • Do not assume caught unknown rejections are Error instances (external/WASM libraries can reject with non-Errors) — use getErrorMessage from @/lib/get-error-message.
  • Handle an error's user-facing side effect (toast or inline alert) in a single layer — do not toast and also rethrow to a caller that surfaces errors (or leave an unhandled rejection).

Больше skills от supabase

ask-the-docs
supabase
Отвечайте на вопросы о приложении документации Supabase (apps/docs), используя документированную архитектуру, конвейер сборки и заметки о паттернах рецензирования, и применяйте проектирование функций…
clickhouse-logs-queries
supabase
Write, review, and migrate Supabase logs queries against the ClickHouse-backed `logs` table (the `logs.all.otel` analytics endpoint). Use this whenever a task…
copywriting
supabase
Писать или проверять UI-копирайтинг (кнопки, метки, пустые состояния, сообщения об ошибках, подсказки, тексты форм) в любом месте монорепозитория. Загружайте его перед выпуском или ревью любого…
dev-toolbar-review
supabase
Используйте при проверке PR, которые затрагивают packages/dev-tools/, packages/common/posthog-client.ts,
docs-content
supabase
Пишите, редактируйте, систематизируйте и проверяйте контент Supabase в любом месте apps/docs — руководства, пояснения, обучающие материалы, записи по устранению неполадок, справочную документацию и…
e2e-studio-tests
supabase
Запускать e2e тесты в приложении Studio. Используйте, когда требуется запустить e2e тесты, студийные тесты, тесты Playwright или протестировать функцию.
pm-the-docs
supabase
Docs-PM поддержка принятия решений для процесса авторской работы "Write the docs" — принимает решения об аудитории, этапах и сквозных областях охвата на этапах Frame и Shape,…
react-hook-form
supabase
Корректное использование React Hook Form в любом месте монорепозитория — поток данных, подписки, сброс, состояние dirty, числовые поля и правила контролируемых инпутов. Загрузите это…