Skip to content

An AI-powered search engine with a generative UI

Avoid showing raw API errors in chat UI

Yoshiki Miurabe2199e2eb45
diff --git a/components/chat-error.tsx b/components/chat-error.tsx
index 0cf3ac63..9c798601 100644
--- a/components/chat-error.tsx
+++ b/components/chat-error.tsx
@@ -1,5 +1,7 @@
import { AlertCircle } from 'lucide-react'
+import { toPublicErrorPayload } from '@/lib/errors/public-error'
+
import { Card } from '@/components/ui/card'
interface ChatErrorProps {
@@ -9,20 +11,7 @@ interface ChatErrorProps {
export function ChatError({ error }: ChatErrorProps) {
if (!error) return null
- let errorMessage = error instanceof Error ? error.message : error
-
- // Try to parse JSON error response and extract user-friendly message
- try {
- const jsonMatch = errorMessage?.match(/\{.*\}/)
- if (jsonMatch) {
- const parsed = JSON.parse(jsonMatch[0])
- if (parsed.error) {
- errorMessage = parsed.error
- }
- }
- } catch {
- // If parsing fails, use the original error message
- }
+ const errorMessage = toPublicErrorPayload(error).error
return (
<Card className="border-destructive bg-destructive/10 p-4">
diff --git a/components/chat.tsx b/components/chat.tsx
index a98b1003..afdabf6e 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -9,6 +9,10 @@ import { toast } from 'sonner'
import { ChatProvider } from '@/lib/contexts/chat-context'
import { generateId } from '@/lib/db/schema'
+import {
+ getPublicRateLimitDetails,
+ toPublicErrorPayload
+} from '@/lib/errors/public-error'
import { SHORTCUT_EVENTS } from '@/lib/keyboard-shortcuts'
import { stripSpecBlocks } from '@/lib/render/strip-spec-blocks'
import { UploadedFile } from '@/lib/types'
@@ -143,83 +147,29 @@ export function Chat({
},
onError: error => {
isStreamingRef.current = false
- // Handle rate limiting errors from Vercel WAF
- // Check for status codes in error message or specific rate limit indicators
- const errorMessage = error.message?.toLowerCase() || ''
- const isRateLimit =
- error.message?.includes('429') ||
- errorMessage.includes('rate limit') ||
- errorMessage.includes('too many requests') ||
- errorMessage.includes('daily limit')
-
- // Check for authentication errors
- const isAuthError =
- error.message?.includes('401') ||
- errorMessage.includes('unauthorized') ||
- errorMessage.includes('authentication required') ||
- errorMessage.includes('sign in to continue')
-
- if (isRateLimit) {
- // Try to parse JSON error response. The body may include `mode`
- // (e.g. "adaptive") so we can show context-specific guidance.
- let parsedError: {
- error?: string
- resetAt?: number
- remaining?: number
- mode?: string
- } = {}
- try {
- const jsonMatch = error.message?.match(/\{.*\}/)
- if (jsonMatch) {
- parsedError = JSON.parse(jsonMatch[0])
- }
- } catch {
- // Ignore parse errors
- }
-
- const userMessage =
- parsedError.error ||
- 'You have reached your daily chat limit. Please try again tomorrow.'
-
- const details =
- parsedError.mode === 'adaptive'
- ? 'The limit resets at midnight UTC. You can continue using Quick mode without restrictions.'
- : 'The limit resets at midnight UTC.'
+ const publicError = toPublicErrorPayload(error)
+ if (publicError.type === 'rate-limit') {
setErrorModal({
open: true,
type: 'rate-limit',
- message: userMessage,
- details
+ message: publicError.error,
+ details: getPublicRateLimitDetails(publicError)
})
- } else if (isAuthError) {
- // Try to parse JSON for context-specific auth prompts
- // (e.g. adaptive mode requires sign in).
- let parsedAuthError: { error?: string; authRequired?: boolean } = {}
- try {
- const jsonMatch = error.message?.match(/\{.*\}/)
- if (jsonMatch) parsedAuthError = JSON.parse(jsonMatch[0])
- } catch {
- // Ignore parse errors
- }
-
+ } else if (publicError.type === 'auth') {
setErrorModal({
open: true,
type: 'auth',
- message: parsedAuthError.error || error.message
+ message: publicError.error
})
- } else if (
- error.message?.includes('403') ||
- errorMessage.includes('forbidden')
- ) {
+ } else if (publicError.type === 'forbidden') {
setErrorModal({
open: true,
type: 'forbidden',
- message: error.message
+ message: publicError.error
})
} else {
- // For general errors, still use toast for less intrusive notification
- toast.error(`Error in chat: ${error.message}`)
+ toast.error(publicError.error)
}
},
experimental_throttle: 100,
@@ -436,9 +386,7 @@ export function Chat({
await safeRegenerate({ messageId: editedMessageId })
} catch (error) {
console.error('Error during message edit and reload process:', error)
- toast.error(
- `Error processing edited message: ${(error as Error).message}`
- )
+ toast.error(toPublicErrorPayload(error).error)
}
}
@@ -456,7 +404,7 @@ export function Chat({
`Error during reload from message ${reloadFromFollowerMessageId}:`,
error
)
- toast.error(`Failed to reload conversation: ${(error as Error).message}`)
+ toast.error(toPublicErrorPayload(error).error)
}
}
diff --git a/components/dynamic-tool-display.tsx b/components/dynamic-tool-display.tsx
index 3cd2bd8f..e639363b 100644
--- a/components/dynamic-tool-display.tsx
+++ b/components/dynamic-tool-display.tsx
@@ -2,6 +2,8 @@
import React from 'react'
+import { toPublicErrorPayload } from '@/lib/errors/public-error'
+
// This matches the structure from AI SDK v5
type DynamicToolPart =
| {
@@ -62,6 +64,12 @@ export function DynamicToolDisplay({ part }: DynamicToolDisplayProps) {
const toolType = getToolType(part.toolName)
const displayName = getDisplayName(part.toolName)
+ const errorMessage =
+ part.state === 'output-error'
+ ? toPublicErrorPayload(part.errorText, {
+ fallbackMessage: 'Tool execution failed'
+ }).error
+ : undefined
return (
<div className="dynamic-tool-container rounded-lg border p-4 my-2">
@@ -100,7 +108,7 @@ export function DynamicToolDisplay({ part }: DynamicToolDisplayProps) {
<div className="mb-2">
<div className="text-xs text-destructive mb-1">Error:</div>
<div className="text-xs bg-destructive/10 text-destructive p-2 rounded">
- {part.errorText}
+ {errorMessage}
</div>
</div>
)}
diff --git a/components/fetch-section.tsx b/components/fetch-section.tsx
index 40912110..b229f6ce 100644
--- a/components/fetch-section.tsx
+++ b/components/fetch-section.tsx
@@ -3,6 +3,7 @@
import { UseChatHelpers } from '@ai-sdk/react'
import { AlertCircle, Check, ExternalLink, Globe } from 'lucide-react'
+import { toPublicErrorPayload } from '@/lib/errors/public-error'
import { SearchResults as SearchResultsType } from '@/lib/types'
import type { ToolPart, UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'
import { cn } from '@/lib/utils'
@@ -47,7 +48,9 @@ export function FetchSection({
// Check tool state
if (tool.state === 'output-error') {
displayStatus = 'error'
- error = tool.errorText || 'Failed to retrieve content'
+ error = toPublicErrorPayload(tool.errorText, {
+ fallbackMessage: 'Failed to retrieve content'
+ }).error
} else if (!output || isFetching) {
displayStatus = 'fetching'
} else if (fetchResults) {
diff --git a/components/search-section.tsx b/components/search-section.tsx
index 6418cc56..18737f96 100644
--- a/components/search-section.tsx
+++ b/components/search-section.tsx
@@ -3,6 +3,7 @@
import { UseChatHelpers } from '@ai-sdk/react'
import { Check, Search as SearchIcon } from 'lucide-react'
+import { toPublicErrorPayload } from '@/lib/errors/public-error'
import type { SearchResults as TypeSearchResults } from '@/lib/types'
import type { ToolPart, UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'
import { cn } from '@/lib/utils'
@@ -53,7 +54,9 @@ export function SearchSection({
output?.state === 'complete' ? output : undefined
const isError = tool.state === 'output-error'
- const errorMessage = tool.errorText || 'Search failed'
+ const errorMessage = toPublicErrorPayload(tool.errorText, {
+ fallbackMessage: 'Search failed'
+ }).error
const query = tool.input?.query || output?.query || ''
const includeDomains = tool.input?.include_domains
const includeDomainsString =
diff --git a/components/todo-list-content.tsx b/components/todo-list-content.tsx
index 36dbbbb4..af99cde3 100644
--- a/components/todo-list-content.tsx
+++ b/components/todo-list-content.tsx
@@ -2,6 +2,7 @@
import { AlertCircle, Check } from 'lucide-react'
+import { toPublicErrorPayload } from '@/lib/errors/public-error'
import type { TodoItem } from '@/lib/types/ai'
import { cn } from '@/lib/utils'
@@ -53,10 +54,14 @@ export function TodoListContent({
}
if (errorText) {
+ const publicError = toPublicErrorPayload(errorText, {
+ fallbackMessage: 'Failed to process todos'
+ })
+
return (
<div className="flex items-center gap-2 p-4 text-red-600">
<AlertCircle className="size-4" />
- <span>Error: {errorText}</span>
+ <span>Error: {publicError.error}</span>
</div>
)
}
diff --git a/components/tool-todo-display.tsx b/components/tool-todo-display.tsx
index 278331bc..8b3c8147 100644
--- a/components/tool-todo-display.tsx
+++ b/components/tool-todo-display.tsx
@@ -1,5 +1,6 @@
import { Check, ListTodo } from 'lucide-react'
+import { toPublicErrorPayload } from '@/lib/errors/public-error'
import { Part, TodoItem } from '@/lib/types/ai'
import { cn } from '@/lib/utils'
@@ -37,6 +38,7 @@ export function ToolTodoDisplay({
tool,
state,
output,
+ errorText,
toolCallId,
isOpen = false,
onOpenChange,
@@ -53,6 +55,12 @@ export function ToolTodoDisplay({
: 0)
const totalCount =
output?.totalCount ?? (output?.todos ? output.todos.length : 0)
+ const errorMessage =
+ state === 'output-error'
+ ? toPublicErrorPayload(errorText ?? output?.message, {
+ fallbackMessage: 'Todo tool failed'
+ }).error
+ : undefined
const isLoading = state === 'input-streaming' || state === 'input-available'
@@ -154,11 +162,9 @@ export function ToolTodoDisplay({
className="pb-1"
/>
) : state === 'output-error' ? (
- <div className="px-3 pb-3 text-xs text-destructive">{`Todo tool failed${
- output && 'message' in output && output.message
- ? `: ${output.message}`
- : ''
- }`}</div>
+ <div className="px-3 pb-3 text-xs text-destructive">
+ {errorMessage}
+ </div>
) : null}
</div>
</div>
diff --git a/lib/errors/__tests__/public-error.test.ts b/lib/errors/__tests__/public-error.test.ts
new file mode 100644
index 00000000..b86d3269
--- /dev/null
+++ b/lib/errors/__tests__/public-error.test.ts
@@ -0,0 +1,186 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ createPublicErrorResponse,
+ getPublicRateLimitDetails,
+ serializePublicError,
+ toPublicErrorPayload
+} from '@/lib/errors/public-error'
+
+describe('public error mapping', () => {
+ it('hides provider billing errors', () => {
+ const payload = toPublicErrorPayload(
+ new Error(
+ 'Billing hard limit has been reached for this OpenAI organization.'
+ )
+ )
+
+ expect(payload.code).toBe('provider_billing')
+ expect(payload.error).toBe('The AI service is currently unavailable.')
+ expect(payload.error.toLowerCase()).not.toContain('billing')
+ expect(payload.error.toLowerCase()).not.toContain('organization')
+ })
+
+ it('hides provider quota errors from nested JSON responses', () => {
+ const payload = toPublicErrorPayload(
+ JSON.stringify({
+ error: {
+ message:
+ 'You exceeded your current quota, please check your plan and billing details.',
+ code: 'insufficient_quota'
+ }
+ })
+ )
+
+ expect(payload.code).toBe('provider_quota')
+ expect(payload.error).toBe('The AI service is currently unavailable.')
+ expect(payload.error.toLowerCase()).not.toContain('quota')
+ expect(payload.error.toLowerCase()).not.toContain('billing')
+ })
+
+ it('does not treat unrelated log-in wording as user authentication', () => {
+ const payload = toPublicErrorPayload(
+ new Error('failed to log in to the database connection pool')
+ )
+
+ expect(payload.type).toBe('general')
+ expect(payload.code).toBe('provider_unavailable')
+ expect(payload.error).toBe(
+ 'We could not generate a response. Please try again.'
+ )
+ })
+
+ it('hides provider API key configuration errors', () => {
+ const payload = toPublicErrorPayload(
+ new Error(
+ "OpenAI API key is missing. Pass it using the 'apiKey' parameter."
+ )
+ )
+
+ expect(payload.code).toBe('provider_auth')
+ expect(payload.error).toBe(
+ 'The AI service is not configured correctly. Please try again later.'
+ )
+ expect(payload.error.toLowerCase()).not.toContain('api key')
+ })
+
+ it('preserves intentional app rate-limit payloads', () => {
+ const payload = toPublicErrorPayload(
+ JSON.stringify({
+ error:
+ 'Daily limit for Adaptive mode reached. Please try again tomorrow, or continue in Quick mode.',
+ remaining: 0,
+ resetAt: 1767139200000,
+ limit: 30,
+ mode: 'adaptive'
+ })
+ )
+
+ expect(payload.type).toBe('rate-limit')
+ expect(payload.code).toBe('rate_limit')
+ expect(payload.error).toBe(
+ 'Daily limit for Adaptive mode reached. Please try again tomorrow, or continue in Quick mode.'
+ )
+ expect(payload.mode).toBe('adaptive')
+ expect(getPublicRateLimitDetails(payload)).toBe(
+ 'The limit resets at midnight UTC. You can continue using Quick mode without restrictions.'
+ )
+ })
+
+ it('does not preserve raw text just because a parsed payload has a known code', () => {
+ const payload = toPublicErrorPayload(
+ JSON.stringify({
+ code: 'rate_limit',
+ error:
+ 'Provider rate_limit: internal tenant abc123 exceeded reserved capacity'
+ })
+ )
+
+ expect(payload.type).toBe('rate-limit')
+ expect(payload.code).toBe('rate_limit')
+ expect(payload.error).toBe(
+ 'The AI service is receiving too many requests. Please try again shortly.'
+ )
+ expect(payload.error).not.toContain('tenant')
+ expect(payload.error).not.toContain('abc123')
+ })
+
+ it('parses Error objects that contain public JSON payloads', () => {
+ const payload = toPublicErrorPayload(
+ new Error(
+ JSON.stringify({
+ error:
+ 'Sign in to use Adaptive mode. Quick mode remains available without an account.',
+ mode: 'adaptive',
+ authRequired: true
+ })
+ )
+ )
+
+ expect(payload.type).toBe('auth')
+ expect(payload.code).toBe('auth_required')
+ expect(payload.authRequired).toBe(true)
+ expect(payload.error).toBe(
+ 'Sign in to use Adaptive mode. Quick mode remains available without an account.'
+ )
+ })
+
+ it('maps context length errors to useful but sanitized copy', () => {
+ const payload = toPublicErrorPayload(
+ new Error(
+ 'This model has a maximum context length of 128000 tokens. Your messages resulted in 144000 tokens.'
+ )
+ )
+
+ expect(payload.code).toBe('context_length')
+ expect(payload.error).toBe(
+ 'This conversation is too long for the selected model. Start a new chat or shorten your message.'
+ )
+ expect(payload.error).not.toContain('144000')
+ })
+
+ it('serializes public payloads for stream error chunks', () => {
+ const serialized = serializePublicError(
+ new Error('Redis timeout while saving stream results')
+ )
+ const payload = JSON.parse(serialized)
+
+ expect(payload.code).toBe('provider_unavailable')
+ expect(payload.error).toBe(
+ 'We could not generate a response. Please try again.'
+ )
+ expect(serialized).not.toContain('Redis timeout')
+ })
+
+ it('creates JSON error responses without raw messages', async () => {
+ const response = createPublicErrorResponse(
+ new Error(
+ 'Database connection failed with password authentication error'
+ ),
+ { status: 500 }
+ )
+
+ expect(response.status).toBe(500)
+ expect(response.headers.get('content-type')).toBe('application/json')
+
+ const payload = await response.json()
+ expect(payload.error).toBe(
+ 'We could not generate a response. Please try again.'
+ )
+ expect(JSON.stringify(payload).toLowerCase()).not.toContain('password')
+ })
+
+ it('handles circular thrown objects without crashing', () => {
+ const circular: Record<string, unknown> = {
+ reason: 'database password leak'
+ }
+ circular.self = circular
+
+ const payload = toPublicErrorPayload(circular)
+
+ expect(payload.type).toBe('general')
+ expect(payload.error).toBe(
+ 'We could not generate a response. Please try again.'
+ )
+ })
+})
diff --git a/lib/errors/public-error.ts b/lib/errors/public-error.ts
new file mode 100644
index 00000000..139203b2
--- /dev/null
+++ b/lib/errors/public-error.ts
@@ -0,0 +1,501 @@
+export type PublicErrorType = 'rate-limit' | 'auth' | 'forbidden' | 'general'
+
+export type PublicErrorCode =
+ | 'auth_required'
+ | 'bad_request'
+ | 'context_length'
+ | 'forbidden'
+ | 'model_unavailable'
+ | 'provider_auth'
+ | 'provider_billing'
+ | 'provider_quota'
+ | 'provider_rate_limit'
+ | 'provider_unavailable'
+ | 'rate_limit'
+ | 'unknown'
+
+export type PublicErrorPayload = {
+ error: string
+ code: PublicErrorCode
+ type: PublicErrorType
+ details?: string
+ retryable?: boolean
+ authRequired?: boolean
+ resetAt?: number
+ remaining?: number
+ limit?: number
+ mode?: string
+}
+
+type PublicErrorOptions = {
+ status?: number
+ fallbackMessage?: string
+}
+
+type ErrorSnapshot = {
+ message: string
+ statusCode?: number
+ code?: string | number
+ name?: string
+}
+
+const DEFAULT_PUBLIC_ERROR_MESSAGE =
+ 'We could not generate a response. Please try again.'
+
+const PUBLIC_ERROR_CODES: ReadonlySet<string> = new Set([
+ 'auth_required',
+ 'bad_request',
+ 'context_length',
+ 'forbidden',
+ 'model_unavailable',
+ 'provider_auth',
+ 'provider_billing',
+ 'provider_quota',
+ 'provider_rate_limit',
+ 'provider_unavailable',
+ 'rate_limit',
+ 'unknown'
+])
+
+const PUBLIC_ERROR_TYPES: ReadonlySet<string> = new Set([
+ 'rate-limit',
+ 'auth',
+ 'forbidden',
+ 'general'
+])
+
+const BILLING_PATTERNS = [
+ /\bbilling\b/i,
+ /\bcredits?\b/i,
+ /\bpayment\b/i,
+ /\bsubscription\b/i,
+ /\bbalance\b/i,
+ /insufficient[_\s-]?quota/i,
+ /insufficient[_\s-]?credit/i,
+ /exceeded your current quota/i,
+ /quota exceeded/i
+]
+
+const PROVIDER_AUTH_PATTERNS = [
+ /\bapi[_\s-]?key\b/i,
+ /\baccess token\b/i,
+ /\bbearer token\b/i,
+ /\bcredential/i,
+ /\binvalid key\b/i,
+ /\bmissing key\b/i,
+ /\bincorrect api key\b/i
+]
+
+const AUTH_REQUIRED_PATTERNS = [
+ /authentication required/i,
+ /not authenticated/i,
+ /please sign in/i,
+ /sign in to/i,
+ /\blog ?in to (your )?account\b/i,
+ /\blog ?in to continue\b/i
+]
+
+const RATE_LIMIT_PATTERNS = [
+ /\brate[_\s-]?limit/i,
+ /too many requests/i,
+ /daily limit/i,
+ /\b429\b/
+]
+
+const CONTEXT_LENGTH_PATTERNS = [
+ /context length/i,
+ /context window/i,
+ /maximum context/i,
+ /token limit/i,
+ /too many tokens/i
+]
+
+const MODEL_UNAVAILABLE_PATTERNS = [
+ /model .*not found/i,
+ /no such model/i,
+ /model .*unavailable/i,
+ /unsupported model/i
+]
+
+const SYSTEM_PATTERNS = [
+ /internal server error/i,
+ /service unavailable/i,
+ /bad gateway/i,
+ /gateway timeout/i,
+ /database/i,
+ /redis/i,
+ /postgres/i,
+ /supabase/i,
+ /stack/i,
+ /trace/i,
+ /exception/i
+]
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null
+}
+
+function asPublicErrorCode(value: unknown): PublicErrorCode | undefined {
+ return typeof value === 'string' && PUBLIC_ERROR_CODES.has(value)
+ ? (value as PublicErrorCode)
+ : undefined
+}
+
+function asPublicErrorType(value: unknown): PublicErrorType | undefined {
+ return typeof value === 'string' && PUBLIC_ERROR_TYPES.has(value)
+ ? (value as PublicErrorType)
+ : undefined
+}
+
+function getString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value : undefined
+}
+
+function getNumber(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
+}
+
+function matchesAny(value: string, patterns: RegExp[]): boolean {
+ return patterns.some(pattern => pattern.test(value))
+}
+
+function extractJsonCandidate(value: string): unknown | null {
+ const trimmed = value.trim()
+ if (!trimmed) return null
+
+ try {
+ return JSON.parse(trimmed)
+ } catch {
+ // AI SDK sometimes wraps a JSON response body in Error(message). Keep a
+ // conservative fallback for messages that include that body with prefixes.
+ }
+
+ const match = trimmed.match(/\{[\s\S]*\}/)
+ if (!match) return null
+
+ try {
+ return JSON.parse(match[0])
+ } catch {
+ return null
+ }
+}
+
+function extractNestedMessage(
+ value: Record<string, unknown>
+): string | undefined {
+ const topLevelError = getString(value.error)
+ if (topLevelError) return topLevelError
+
+ const topLevelMessage = getString(value.message)
+ if (topLevelMessage) return topLevelMessage
+
+ if (isRecord(value.error)) {
+ return getString(value.error.message)
+ }
+}
+
+function safeStringifyRecord(value: Record<string, unknown>): string {
+ try {
+ return JSON.stringify(value, Object.keys(value).sort())
+ } catch {
+ return String(value)
+ }
+}
+
+function snapshotError(error: unknown): ErrorSnapshot {
+ if (typeof error === 'string') {
+ return { message: error }
+ }
+
+ if (error instanceof Error) {
+ const record = error as Error & Record<string, unknown>
+ return {
+ message: error.message,
+ statusCode:
+ getNumber(record.statusCode) ??
+ getNumber(record.status) ??
+ getNumber(record.cause),
+ code:
+ (typeof record.code === 'string' || typeof record.code === 'number'
+ ? record.code
+ : undefined) ??
+ (isRecord(record.data) &&
+ (typeof record.data.code === 'string' ||
+ typeof record.data.code === 'number')
+ ? record.data.code
+ : undefined),
+ name: error.name
+ }
+ }
+
+ if (isRecord(error)) {
+ return {
+ message: extractNestedMessage(error) ?? safeStringifyRecord(error),
+ statusCode: getNumber(error.statusCode) ?? getNumber(error.status),
+ code:
+ typeof error.code === 'string' || typeof error.code === 'number'
+ ? error.code
+ : undefined,
+ name: getString(error.name)
+ }
+ }
+
+ return { message: String(error) }
+}
+
+function typeForCode(code: PublicErrorCode): PublicErrorType {
+ switch (code) {
+ case 'auth_required':
+ return 'auth'
+ case 'forbidden':
+ return 'forbidden'
+ case 'provider_rate_limit':
+ case 'rate_limit':
+ return 'rate-limit'
+ default:
+ return 'general'
+ }
+}
+
+function classifyError(snapshot: ErrorSnapshot, fallbackMessage?: string) {
+ const message = snapshot.message
+ const status = snapshot.statusCode
+ const combined = [message, snapshot.code, snapshot.name]
+ .filter(value => value !== undefined)
+ .join(' ')
+
+ if (status === 403 || /\bforbidden\b/i.test(combined)) {
+ return {
+ code: 'forbidden' as const,
+ type: 'forbidden' as const,
+ error: 'You do not have permission to access this resource.',
+ retryable: false
+ }
+ }
+
+ if (matchesAny(combined, PROVIDER_AUTH_PATTERNS)) {
+ return {
+ code: 'provider_auth' as const,
+ type: 'general' as const,
+ error:
+ 'The AI service is not configured correctly. Please try again later.',
+ retryable: false
+ }
+ }
+
+ if (status === 401 || matchesAny(combined, AUTH_REQUIRED_PATTERNS)) {
+ return {
+ code: 'auth_required' as const,
+ type: 'auth' as const,
+ error: 'Please sign in to continue.',
+ retryable: false,
+ authRequired: true
+ }
+ }
+
+ if (matchesAny(combined, BILLING_PATTERNS)) {
+ return {
+ code: /quota/i.test(combined)
+ ? ('provider_quota' as const)
+ : ('provider_billing' as const),
+ type: 'general' as const,
+ error: 'The AI service is currently unavailable.',
+ retryable: false
+ }
+ }
+
+ if (status === 429 || matchesAny(combined, RATE_LIMIT_PATTERNS)) {
+ const isDailyLimit = /daily limit/i.test(combined)
+ return {
+ code: isDailyLimit
+ ? ('rate_limit' as const)
+ : ('provider_rate_limit' as const),
+ type: 'rate-limit' as const,
+ error: isDailyLimit
+ ? 'You have reached your daily chat limit. Please try again tomorrow.'
+ : 'The AI service is receiving too many requests. Please try again shortly.',
+ details: isDailyLimit
+ ? 'The limit resets at midnight UTC.'
+ : 'Please wait a moment before trying again.',
+ retryable: !isDailyLimit
+ }
+ }
+
+ if (matchesAny(combined, CONTEXT_LENGTH_PATTERNS)) {
+ return {
+ code: 'context_length' as const,
+ type: 'general' as const,
+ error:
+ 'This conversation is too long for the selected model. Start a new chat or shorten your message.',
+ retryable: false
+ }
+ }
+
+ if (matchesAny(combined, MODEL_UNAVAILABLE_PATTERNS)) {
+ return {
+ code: 'model_unavailable' as const,
+ type: 'general' as const,
+ error: 'The selected model is unavailable. Please choose another model.',
+ retryable: false
+ }
+ }
+
+ if (status === 400) {
+ return {
+ code: 'bad_request' as const,
+ type: 'general' as const,
+ error: fallbackMessage ?? 'The request could not be processed.',
+ retryable: false
+ }
+ }
+
+ if (
+ status === 503 ||
+ status === 502 ||
+ status === 504 ||
+ matchesAny(combined, SYSTEM_PATTERNS)
+ ) {
+ return {
+ code: 'provider_unavailable' as const,
+ type: 'general' as const,
+ error: fallbackMessage ?? DEFAULT_PUBLIC_ERROR_MESSAGE,
+ retryable: true
+ }
+ }
+
+ return {
+ code: 'unknown' as const,
+ type: 'general' as const,
+ error: fallbackMessage ?? DEFAULT_PUBLIC_ERROR_MESSAGE,
+ retryable: true
+ }
+}
+
+function isIntentionalPublicPayload(
+ value: Record<string, unknown>,
+ code: PublicErrorCode
+): boolean {
+ return (
+ Boolean(value.authRequired) ||
+ getNumber(value.resetAt) !== undefined ||
+ getNumber(value.remaining) !== undefined ||
+ (code === 'rate_limit' && getString(value.mode) !== undefined)
+ )
+}
+
+function fromParsedPayload(
+ value: Record<string, unknown>,
+ options: PublicErrorOptions
+): PublicErrorPayload | null {
+ const message = extractNestedMessage(value)
+ if (!message) return null
+
+ const status = getNumber(value.status) ?? options.status
+ const classification = classifyError(
+ {
+ message,
+ statusCode: status,
+ code: getString(value.code) ?? getString(value.errorCode),
+ name: getString(value.name)
+ },
+ options.fallbackMessage
+ )
+ const code = asPublicErrorCode(value.code) ?? classification.code
+ const type = asPublicErrorType(value.type) ?? typeForCode(code)
+ const preserveMessage = isIntentionalPublicPayload(value, code)
+
+ return {
+ error: preserveMessage ? message : classification.error,
+ code,
+ type,
+ details: getString(value.details) ?? classification.details,
+ retryable:
+ typeof value.retryable === 'boolean'
+ ? value.retryable
+ : classification.retryable,
+ authRequired:
+ typeof value.authRequired === 'boolean'
+ ? value.authRequired
+ : classification.authRequired,
+ resetAt: getNumber(value.resetAt),
+ remaining: getNumber(value.remaining),
+ limit: getNumber(value.limit),
+ mode: getString(value.mode)
+ }
+}
+
+export function toPublicErrorPayload(
+ error: unknown,
+ options: PublicErrorOptions = {}
+): PublicErrorPayload {
+ if (typeof error === 'string') {
+ const parsed = extractJsonCandidate(error)
+ if (isRecord(parsed)) {
+ const payload = fromParsedPayload(parsed, options)
+ if (payload) return payload
+ }
+ } else if (error instanceof Error) {
+ const parsed = extractJsonCandidate(error.message)
+ if (isRecord(parsed)) {
+ const payload = fromParsedPayload(parsed, options)
+ if (payload) return payload
+ }
+ } else if (isRecord(error)) {
+ const payload = fromParsedPayload(error, options)
+ if (payload) return payload
+ }
+
+ const snapshot = snapshotError(error)
+ const classification = classifyError(
+ { ...snapshot, statusCode: snapshot.statusCode ?? options.status },
+ options.fallbackMessage
+ )
+
+ return {
+ error: classification.error,
+ code: classification.code,
+ type: classification.type,
+ details: classification.details,
+ retryable: classification.retryable,
+ authRequired: classification.authRequired
+ }
+}
+
+export function serializePublicError(
+ error: unknown,
+ options: PublicErrorOptions = {}
+): string {
+ return JSON.stringify(toPublicErrorPayload(error, options))
+}
+
+export function createPublicErrorResponse(
+ error: unknown,
+ init: ResponseInit & PublicErrorOptions = {}
+): Response {
+ const { fallbackMessage, status = 500, ...responseInit } = init
+ return new Response(
+ serializePublicError(error, { fallbackMessage, status }),
+ {
+ ...responseInit,
+ status,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...Object.fromEntries(new Headers(responseInit.headers).entries())
+ }
+ }
+ )
+}
+
+export function getPublicRateLimitDetails(error: PublicErrorPayload): string {
+ if (error.mode === 'adaptive') {
+ return 'The limit resets at midnight UTC. You can continue using Quick mode without restrictions.'
+ }
+
+ if (error.details) return error.details
+
+ if (error.code === 'provider_rate_limit') {
+ return 'Please wait a moment before trying again.'
+ }
+
+ return 'The limit resets at midnight UTC.'
+}
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 867341ba..38406d48 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -8,6 +8,10 @@ import { randomUUID } from 'crypto'
import { Langfuse } from 'langfuse'
import { researcher } from '@/lib/agents/researcher'
+import {
+ createPublicErrorResponse,
+ serializePublicError
+} from '@/lib/errors/public-error'
import { isTracingEnabled } from '@/lib/utils/telemetry'
import { loadChat } from '../actions/chat'
@@ -217,7 +221,8 @@ export async function createChatStreamResponse(
}
},
onError: (error: unknown) => {
- return error instanceof Error ? error.message : String(error)
+ console.error('Stream response error:', error)
+ return serializePublicError(error)
},
consumeSseStream: consumeStream
})
@@ -226,8 +231,7 @@ export async function createChatStreamResponse(
await langfuse.flushAsync()
}
console.error('Stream execution error:', error)
- const errorMessage = error instanceof Error ? error.message : String(error)
- return new Response(errorMessage, {
+ return createPublicErrorResponse(error, {
status: 500,
statusText: 'Internal Server Error'
})
diff --git a/lib/streaming/create-ephemeral-chat-stream-response.ts b/lib/streaming/create-ephemeral-chat-stream-response.ts
index 80edf300..ec8de1e4 100644
--- a/lib/streaming/create-ephemeral-chat-stream-response.ts
+++ b/lib/streaming/create-ephemeral-chat-stream-response.ts
@@ -9,6 +9,10 @@ import { randomUUID } from 'crypto'
import { Langfuse } from 'langfuse'
import { researcher } from '@/lib/agents/researcher'
+import {
+ createPublicErrorResponse,
+ serializePublicError
+} from '@/lib/errors/public-error'
import { isTracingEnabled } from '@/lib/utils/telemetry'
import {
@@ -112,7 +116,8 @@ export async function createEphemeralChatStreamResponse(
}
},
onError: (error: unknown) => {
- return error instanceof Error ? error.message : String(error)
+ console.error('Ephemeral stream response error:', error)
+ return serializePublicError(error)
},
consumeSseStream: consumeStream
})
@@ -120,8 +125,8 @@ export async function createEphemeralChatStreamResponse(
if (langfuse) {
await langfuse.flushAsync()
}
- const message = error instanceof Error ? error.message : String(error)
- return new Response(message, {
+ console.error('Ephemeral stream execution error:', error)
+ return createPublicErrorResponse(error, {
status: 500,
statusText: 'Internal Server Error'
})