-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy patherrors.ts
More file actions
372 lines (335 loc) · 10.1 KB
/
errors.ts
File metadata and controls
372 lines (335 loc) · 10.1 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/**
* CLI Error Hierarchy
*
* Unified error classes for consistent error handling across the CLI.
*/
import {
buildBillingUrl,
buildOrgSettingsUrl,
buildSeerSettingsUrl,
} from "./sentry-urls.js";
/**
* Base class for all CLI errors.
*
* @param message - Error message for display
* @param exitCode - Process exit code (default: 1)
*/
export class CliError extends Error {
readonly exitCode: number;
constructor(message: string, exitCode = 1) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
}
/**
* Format error for user display. Override in subclasses to add details.
*/
format(): string {
return this.message;
}
}
/**
* API request errors from Sentry.
*
* @param message - Error summary
* @param status - HTTP status code
* @param detail - Detailed error message from API response
* @param endpoint - API endpoint that failed
*/
export class ApiError extends CliError {
readonly status: number;
readonly detail?: string;
readonly endpoint?: string;
constructor(
message: string,
status: number,
detail?: string,
endpoint?: string
) {
super(message);
this.name = "ApiError";
this.status = status;
this.detail = detail;
this.endpoint = endpoint;
}
override format(): string {
let msg = this.message;
if (this.detail && this.detail !== this.message) {
msg += `\n ${this.detail}`;
}
return msg;
}
}
export type AuthErrorReason = "not_authenticated" | "expired" | "invalid";
/** Options for AuthError */
export type AuthErrorOptions = {
/** Skip auto-login flow when this error is caught (for auth commands) */
skipAutoAuth?: boolean;
};
/**
* Authentication errors.
*
* @param reason - Type of auth failure
* @param message - Custom message (uses default if not provided)
* @param options - Additional options (e.g., skipAutoAuth for auth commands)
*/
export class AuthError extends CliError {
readonly reason: AuthErrorReason;
/** When true, the auto-login flow should not be triggered for this error */
readonly skipAutoAuth: boolean;
constructor(
reason: AuthErrorReason,
message?: string,
options?: AuthErrorOptions
) {
const defaultMessages: Record<AuthErrorReason, string> = {
not_authenticated: "Not authenticated. Run 'sentry auth login' first.",
expired:
"Authentication expired. Run 'sentry auth login' to re-authenticate.",
invalid: "Invalid authentication token.",
};
super(message ?? defaultMessages[reason]);
this.name = "AuthError";
this.reason = reason;
this.skipAutoAuth = options?.skipAutoAuth ?? false;
}
}
/**
* Configuration or DSN errors.
*
* @param message - Error description
* @param suggestion - Helpful hint for resolving the error
*/
export class ConfigError extends CliError {
readonly suggestion?: string;
constructor(message: string, suggestion?: string) {
super(message);
this.name = "ConfigError";
this.suggestion = suggestion;
}
override format(): string {
let msg = this.message;
if (this.suggestion) {
msg += `\n\nSuggestion: ${this.suggestion}`;
}
return msg;
}
}
const DEFAULT_CONTEXT_ALTERNATIVES = [
"Run from a directory with a Sentry-configured project",
"Set SENTRY_DSN environment variable",
] as const;
/**
* Build the formatted context error message with usage hints.
*
* @param resource - What is required (e.g., "Organization")
* @param command - Usage example command
* @param alternatives - Alternative ways to provide the context
* @returns Formatted multi-line error message
*/
function buildContextMessage(
resource: string,
command: string,
alternatives: string[]
): string {
const lines = [
`${resource} is required.`,
"",
"Specify it using:",
` ${command}`,
];
if (alternatives.length > 0) {
lines.push("", "Or:");
for (const alt of alternatives) {
lines.push(` - ${alt}`);
}
}
return lines.join("\n");
}
/**
* Missing required context errors (org, project, etc).
*
* Provides consistent error formatting with usage hints and alternatives.
*
* @param resource - What is required (e.g., "Organization", "Organization and project")
* @param command - Primary usage example (e.g., "sentry org view <org-slug>")
* @param alternatives - Alternative ways to resolve (defaults to DSN/project detection hints)
*/
export class ContextError extends CliError {
readonly resource: string;
readonly command: string;
readonly alternatives: string[];
constructor(
resource: string,
command: string,
alternatives: string[] = [...DEFAULT_CONTEXT_ALTERNATIVES]
) {
// Include full formatted message so it's shown even when caught by external handlers
super(buildContextMessage(resource, command, alternatives));
this.name = "ContextError";
this.resource = resource;
this.command = command;
this.alternatives = alternatives;
}
override format(): string {
// Message already contains the formatted output
return this.message;
}
}
/**
* Input validation errors.
*
* @param message - Validation failure description
* @param field - Name of the invalid field
*/
export class ValidationError extends CliError {
readonly field?: string;
constructor(message: string, field?: string) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
/**
* OAuth device flow errors (RFC 8628).
*
* @param code - OAuth error code (e.g., "authorization_pending", "slow_down")
* @param description - Human-readable error description
*/
export class DeviceFlowError extends CliError {
readonly code: string;
constructor(code: string, description?: string) {
super(description ?? code);
this.name = "DeviceFlowError";
this.code = code;
}
}
// Upgrade Errors
export type UpgradeErrorReason =
| "unknown_method"
| "unsupported_operation"
| "network_error"
| "execution_failed"
| "version_not_found";
/**
* Upgrade-related errors.
*
* @param reason - Type of upgrade failure
* @param message - Custom message (uses default if not provided)
*/
export class UpgradeError extends CliError {
readonly reason: UpgradeErrorReason;
constructor(reason: UpgradeErrorReason, message?: string) {
const defaultMessages: Record<UpgradeErrorReason, string> = {
unknown_method:
"Could not detect installation method. Use --method to specify.",
unsupported_operation:
"This operation is not supported for this installation method.",
network_error: "Failed to fetch version information.",
execution_failed: "Upgrade command failed.",
version_not_found: "The specified version was not found.",
};
super(message ?? defaultMessages[reason]);
this.name = "UpgradeError";
this.reason = reason;
}
}
// Seer Errors
export type SeerErrorReason = "not_enabled" | "no_budget" | "ai_disabled";
/**
* Seer-specific errors with actionable suggestions.
*
* @param reason - Type of Seer failure
* @param orgSlug - Organization slug for constructing settings URLs
*/
export class SeerError extends CliError {
readonly reason: SeerErrorReason;
readonly orgSlug?: string;
constructor(reason: SeerErrorReason, orgSlug?: string) {
const messages: Record<SeerErrorReason, string> = {
not_enabled: "Seer is not enabled for this organization.",
no_budget: "Seer requires a paid plan.",
ai_disabled: "AI features are disabled for this organization.",
};
super(messages[reason]);
this.name = "SeerError";
this.reason = reason;
this.orgSlug = orgSlug;
}
override format(): string {
// When org slug is known, provide direct URLs to settings
if (this.orgSlug) {
const suggestions: Record<SeerErrorReason, string> = {
not_enabled: `To enable Seer:\n ${buildSeerSettingsUrl(this.orgSlug)}`,
no_budget: `To use Seer features, upgrade your plan:\n ${buildBillingUrl(this.orgSlug, "seer")}`,
ai_disabled: `To enable AI features:\n ${buildOrgSettingsUrl(this.orgSlug, "hideAiFeatures")}`,
};
return `${this.message}\n\n${suggestions[this.reason]}`;
}
// Fallback when org slug is unknown - give generic guidance
const fallbackSuggestions: Record<SeerErrorReason, string> = {
not_enabled:
"To enable Seer, visit your organization's Seer settings in Sentry.",
no_budget:
"To use Seer features, upgrade your plan in your organization's billing settings.",
ai_disabled:
"To enable AI features, check the 'Hide AI Features' setting in your organization settings.",
};
return `${this.message}\n\n${fallbackSuggestions[this.reason]}`;
}
}
// Error Utilities
/**
* Convert an unknown value to a human-readable string.
*
* Handles Error instances (`.message`), plain objects (`JSON.stringify`),
* strings (as-is), and other primitives (`String()`).
* Use this instead of bare `String(value)` when the value might be a
* plain object — `String({})` produces the unhelpful `"[object Object]"`.
*
* @param value - Any thrown or unknown value
* @returns Human-readable string representation
*/
export function stringifyUnknown(value: unknown): string {
if (typeof value === "string") {
return value;
}
if (value instanceof Error) {
return value.message;
}
if (value && typeof value === "object") {
// JSON.stringify can throw on circular references or BigInt values.
// Fall back to String() which is always safe.
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
return String(value);
}
/**
* Format any error for user display.
* Uses CliError.format() for CLI errors, falls back to stringifyUnknown.
*
* @param error - Any thrown value
* @returns Formatted error string
*/
export function formatError(error: unknown): string {
if (error instanceof CliError) {
return error.format();
}
return stringifyUnknown(error);
}
/**
* Get process exit code for an error.
*
* @param error - Any thrown value
* @returns Exit code (from CliError.exitCode or 1 for other errors)
*/
export function getExitCode(error: unknown): number {
if (error instanceof CliError) {
return error.exitCode;
}
return 1;
}