-
Notifications
You must be signed in to change notification settings - Fork 601
Expand file tree
/
Copy patherror-handling.ts
More file actions
78 lines (68 loc) · 2.22 KB
/
error-handling.ts
File metadata and controls
78 lines (68 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { env } from '@codebuff/common/env'
import type { ChatMessage } from '../types/chat'
import { IS_FREEBUFF } from './constants'
const defaultAppUrl = env.NEXT_PUBLIC_CODEBUFF_APP_URL || 'https://codebuff.com'
// Normalize unknown errors to a user-facing string.
const extractErrorMessage = (error: unknown, fallback: string): string => {
if (typeof error === 'string') {
return error
}
if (error instanceof Error && error.message) {
return error.message + (error.stack ? `\n\n${error.stack}` : '')
}
if (error && typeof error === 'object' && 'message' in error) {
const candidate = (error as { message: unknown }).message
if (typeof candidate === 'string' && candidate.length > 0) {
return candidate
}
}
return fallback
}
/**
* Check if an error indicates the user is out of credits.
* Standardized on statusCode === 402 for payment required detection.
*/
export const isOutOfCreditsError = (error: unknown): boolean => {
if (
error &&
typeof error === 'object' &&
'statusCode' in error &&
(error as { statusCode: unknown }).statusCode === 402
) {
return true
}
return false
}
/**
* Check if an error indicates free mode is not available in the user's country.
* Standardized on statusCode === 403 + error === 'free_mode_unavailable'.
*/
export const isFreeModeUnavailableError = (error: unknown): boolean => {
if (
error &&
typeof error === 'object' &&
'statusCode' in error &&
(error as { statusCode: unknown }).statusCode === 403 &&
'error' in error &&
(error as { error: unknown }).error === 'free_mode_unavailable'
) {
return true
}
return false
}
export const OUT_OF_CREDITS_MESSAGE = `Out of credits. Please add credits at ${defaultAppUrl}/usage`
export const FREE_MODE_UNAVAILABLE_MESSAGE = IS_FREEBUFF
? 'Freebuff is not available in your country.'
: 'Free mode is not available in your country. You can use another mode to continue.'
export const createErrorMessage = (
error: unknown,
aiMessageId: string,
): Partial<ChatMessage> => {
const message = extractErrorMessage(error, 'Unknown error occurred')
return {
id: aiMessageId,
content: `**Error:** ${message}`,
blocks: undefined,
isComplete: true,
}
}