Files
supabase/apps/studio/components/interfaces/ErrorHandling/ErrorMatcher.test.tsx
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

129 lines
4.4 KiB
TypeScript

import { render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { ErrorMatcher } from './ErrorMatcher'
import { ConnectionTimeoutError, UnexpectedError } from '@/lib/errors/studio-errors'
vi.mock('@/lib/telemetry/track', () => ({ useTrack: () => vi.fn() }))
vi.mock('@/state/ai-assistant-state', () => ({
useAiAssistantStateSnapshot: () => ({ newChat: vi.fn() }),
}))
vi.mock('@/state/sidebar-manager-state', () => ({
useSidebarManagerSnapshot: () => ({ openSidebar: vi.fn() }),
}))
vi.mock('@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider', () => ({
SIDEBAR_KEYS: { AI_ASSISTANT: 'ai-assistant' },
}))
vi.mock('./RestartProjectDialog', () => ({
RestartProjectDialog: () => null,
}))
describe('ErrorMatcher', () => {
it('renders the provided title and error message', () => {
render(
<ErrorMatcher
title="Failed to load tables"
error="ERROR: FAILED TO RUN SQL QUERY: CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT."
supportFormParams={{}}
/>
)
expect(screen.getByText('Failed to load tables')).toBeInTheDocument()
expect(
screen.getByText(
'ERROR: FAILED TO RUN SQL QUERY: CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT.'
)
).toBeInTheDocument()
})
it('renders troubleshooting steps for classified errors', () => {
const error = new ConnectionTimeoutError({
message: 'CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT',
})
render(<ErrorMatcher title="Failed to load tables" error={error} supportFormParams={{}} />)
expect(screen.getByText('Try restarting your project')).toBeInTheDocument()
expect(screen.getByText('Try our troubleshooting guide')).toBeInTheDocument()
expect(screen.getByText('Debug with AI')).toBeInTheDocument()
})
it('renders fallback for non-timeout error class carrying a timeout message', () => {
render(
<ErrorMatcher
title="Failed to load tables"
error={new UnexpectedError({ message: 'CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT' })}
supportFormParams={{}}
/>
)
expect(screen.getByText('Failed to load tables')).toBeInTheDocument()
expect(screen.queryByText('Try restarting your project')).not.toBeInTheDocument()
})
it('renders fallback with provided title for unmatched errors', () => {
render(
<ErrorMatcher title="Failed to load tables" error="UNKNOWN ERROR" supportFormParams={{}} />
)
expect(screen.getByText('Failed to load tables')).toBeInTheDocument()
expect(screen.getByText('UNKNOWN ERROR')).toBeInTheDocument()
})
it('renders the caller-provided fallback when the error is unclassified', () => {
render(
<ErrorMatcher
title="Failed to load tables"
error="UNKNOWN ERROR"
supportFormParams={{}}
fallback={<div>Custom fallback</div>}
/>
)
expect(screen.getByText('Custom fallback')).toBeInTheDocument()
})
it('ignores the caller-provided fallback when the error is classified', () => {
const error = new ConnectionTimeoutError({
message: 'CONNECTION TERMINATED DUE TO CONNECTION TIMEOUT',
})
render(
<ErrorMatcher
title="Failed to load tables"
error={error}
supportFormParams={{}}
fallback={<div>Custom fallback</div>}
/>
)
expect(screen.queryByText('Custom fallback')).not.toBeInTheDocument()
expect(screen.getByText('Try restarting your project')).toBeInTheDocument()
})
it('accepts error as object with message property', () => {
render(
<ErrorMatcher
title="Failed to load tables"
error={{ message: 'UNKNOWN ERROR' }}
supportFormParams={{}}
/>
)
expect(screen.getByText('UNKNOWN ERROR')).toBeInTheDocument()
})
it('builds support link with projectRef param', () => {
render(
<ErrorMatcher
title="Failed to load tables"
error="UNKNOWN ERROR"
supportFormParams={{ projectRef: 'my-project' }}
/>
)
expect(screen.getByRole('link', { name: /contact support/i })).toHaveAttribute(
'href',
'/support/new?projectRef=my-project'
)
})
it('builds support link with no params when supportFormParams is omitted', () => {
render(<ErrorMatcher title="Failed to load tables" error="UNKNOWN ERROR" />)
expect(screen.getByRole('link', { name: /contact support/i })).toHaveAttribute(
'href',
'/support/new'
)
})
})