Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 58x 1x 1x 1x 1x 1x 1x 1x 54x 54x 54x 54x 54x 54x 54x 1x 1x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { AuthError } from '@supabase/supabase-js';
import * as crypto from 'crypto';
import { logger } from '../utils/logger';
// Custom error types
export enum ErrorType {
NETWORK = 'NETWORK_ERROR',
AUTH = 'AUTH_ERROR',
VALIDATION = 'VALIDATION_ERROR',
NOT_FOUND = 'NOT_FOUND',
PERMISSION_DENIED = 'PERMISSION_DENIED',
RATE_LIMIT = 'RATE_LIMIT',
SERVER = 'SERVER_ERROR',
DATABASE = 'DATABASE_ERROR',
UNKNOWN = 'UNKNOWN_ERROR',
}
export enum ErrorSeverity {
LOW = 'low',
MEDIUM = 'medium',
HIGH = 'high',
CRITICAL = 'critical',
}
// Initialize logger
const log = logger;
// Base application error class
export class AppError extends Error {
public readonly type: ErrorType;
public readonly severity: ErrorSeverity;
public readonly code?: string;
public readonly details?: any;
public readonly hint?: string;
public readonly timestamp: Date;
public readonly context?: Record<string, any>;
constructor(
message: string,
type: ErrorType = ErrorType.UNKNOWN,
severity: ErrorSeverity = ErrorSeverity.MEDIUM,
code?: string,
details?: any,
hint?: string,
context?: Record<string, any>
) {
super(message);
this.name = 'AppError';
this.type = type;
this.severity = severity;
this.code = code;
this.details = details;
this.hint = hint;
this.timestamp = new Date();
this.context = context;
// Ensure the stack trace points to where the error was thrown
if (Error.captureStackTrace) {
Error.captureStackTrace(this, AppError);
}
}
// Convert to plain object for logging/serialization
toJSON() {
return {
name: this.name,
message: this.message,
type: this.type,
severity: this.severity,
code: this.code,
details: this.details,
hint: this.hint,
timestamp: this.timestamp.toISOString(),
context: this.context,
stack: this.stack,
};
}
}
// Specific error classes
export class NetworkError extends AppError {
constructor(message: string, code?: string, details?: any) {
super(message, ErrorType.NETWORK, ErrorSeverity.MEDIUM, code, details);
this.name = 'NetworkError';
}
}
export class AuthenticationError extends AppError {
constructor(message: string, code?: string, details?: any) {
super(message, ErrorType.AUTH, ErrorSeverity.HIGH, code, details);
this.name = 'AuthenticationError';
}
}
export class ValidationError extends AppError {
public readonly field?: string;
constructor(message: string, field?: string, code?: string, details?: any) {
super(message, ErrorType.VALIDATION, ErrorSeverity.LOW, code, details);
this.name = 'ValidationError';
this.field = field;
}
}
export class NotFoundError extends AppError {
constructor(resource: string, identifier?: string) {
const message = identifier
? `${resource} with identifier '${identifier}' not found`
: `${resource} not found`;
super(message, ErrorType.NOT_FOUND, ErrorSeverity.LOW);
this.name = 'NotFoundError';
}
}
export class PermissionError extends AppError {
constructor(action: string, resource?: string) {
const message = resource
? `Permission denied: cannot ${action} ${resource}`
: `Permission denied: cannot ${action}`;
super(message, ErrorType.PERMISSION_DENIED, ErrorSeverity.HIGH);
this.name = 'PermissionError';
}
}
// Error transformation utilities
export const transformSupabaseError = (error: any): AppError => {
if (!error) {
return new AppError('Unknown error occurred');
}
// Handle PostgrestError (database errors)
if (error.code) {
switch (error.code) {
case 'PGRST116':
return new NotFoundError('Resource');
case '23505':
return new ValidationError(
'This record already exists',
undefined,
error.code,
error.details
);
case '23503':
return new ValidationError(
'Referenced record does not exist',
undefined,
error.code,
error.details
);
case '42501':
return new PermissionError('perform this action');
case 'PGRST301':
return new AppError('Request timeout', ErrorType.NETWORK, ErrorSeverity.MEDIUM, error.code);
default:
return new AppError(
error.message || 'Database error occurred',
ErrorType.DATABASE,
ErrorSeverity.MEDIUM,
error.code,
error.details,
error.hint
);
}
}
// Handle AuthError
if (error instanceof AuthError || error.name === 'AuthError') {
return new AuthenticationError(
error.message || 'Authentication failed',
error.status?.toString(),
error
);
}
// Handle network errors
if (
error.name === 'NetworkError' ||
error.message?.includes('fetch') ||
error.message?.includes('network') ||
error.code === 'NETWORK_ERROR'
) {
return new NetworkError(
'Network connection failed. Please check your internet connection.',
error.code,
error
);
}
// Handle rate limiting
if (error.status === 429 || error.code === 'RATE_LIMIT_EXCEEDED') {
return new AppError(
'Too many requests. Please try again later.',
ErrorType.RATE_LIMIT,
ErrorSeverity.MEDIUM,
error.code
);
}
// Handle server errors
if (error.status >= 500 || error.code?.startsWith('5')) {
return new AppError(
'Server error occurred. Please try again later.',
ErrorType.SERVER,
ErrorSeverity.HIGH,
error.status?.toString() || error.code,
error
);
}
// Generic error handling
return new AppError(
error.message || 'An unexpected error occurred',
ErrorType.UNKNOWN,
ErrorSeverity.MEDIUM,
error.code,
error
);
};
// User-friendly error messages
export const getUserFriendlyMessage = (error: AppError): string => {
switch (error.type) {
case ErrorType.NETWORK:
return 'Connection problem. Please check your internet and try again.';
case ErrorType.AUTH:
return 'Please sign in to continue.';
case ErrorType.VALIDATION:
return error.message; // Validation messages are usually user-friendly
case ErrorType.NOT_FOUND:
return 'The requested item could not be found.';
case ErrorType.PERMISSION_DENIED:
return "You don't have permission to perform this action.";
case ErrorType.RATE_LIMIT:
return "You're doing that too quickly. Please slow down and try again.";
case ErrorType.SERVER:
return 'Something went wrong on our end. Please try again in a moment.';
case ErrorType.DATABASE:
return 'There was a problem saving your data. Please try again.';
default:
return 'Something unexpected happened. Please try again.';
}
};
// Error logging utilities
export interface ErrorLogEntry {
error: AppError;
userId?: string;
userAgent?: string;
url?: string;
timestamp: Date;
sessionId?: string;
buildVersion?: string;
}
export const logError = (
error: AppError,
context?: {
userId?: string;
operation?: string;
component?: string;
source?: string;
additionalData?: Record<string, any>;
}
): void => {
const logEntry: ErrorLogEntry = {
error,
userId: context?.userId,
userAgent: navigator?.userAgent,
url: window?.location?.href,
timestamp: new Date(),
sessionId: getSessionId(),
buildVersion: import.meta.env.VITE_APP_VERSION,
};
// Structured error logging
const logLevel =
error.severity === ErrorSeverity.CRITICAL || error.severity === ErrorSeverity.HIGH
? 'error'
: 'warn';
const logMethod = logLevel === 'error' ? log.error : log.warn;
logMethod(
`${error.name}: ${error.message}`,
{
component: 'ErrorHandler',
action: 'log_error',
metadata: {
errorType: error.type,
errorCode: error.code,
severity: error.severity,
details: error.details,
context: context,
timestamp: error.timestamp,
sessionId: getSessionId(),
buildVersion: import.meta.env.VITE_APP_VERSION,
},
},
error
);
// Send to error reporting service in production
if (import.meta.env.MODE === 'production' && error.severity !== ErrorSeverity.LOW) {
reportErrorToService(logEntry);
}
};
// Error reporting to external service (implement based on your service)
const reportErrorToService = async (logEntry: ErrorLogEntry): Promise<void> => {
try {
// Example: Send to Sentry, LogRocket, or custom error service
// await errorReportingService.captureException(logEntry);
// For now, we'll just store it locally or send to a custom endpoint
if (import.meta.env.VITE_ERROR_REPORTING_ENDPOINT) {
await fetch(import.meta.env.VITE_ERROR_REPORTING_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(logEntry),
});
}
} catch (reportingError) {
log.error(
'Failed to report error to external service',
{
component: 'ErrorHandler',
action: 'report_error',
metadata: {
originalError: logEntry.error?.message,
reportingEndpoint: import.meta.env.VITE_ERROR_REPORTING_ENDPOINT,
},
},
reportingError instanceof Error ? reportingError : new Error(String(reportingError))
);
}
};
// Session ID utilities
let sessionId: string | null = null;
const getSessionId = (): string => {
if (!sessionId) {
// Use a cryptographically secure random value for the session ID
sessionId = `session_${Date.now()}_${crypto.randomBytes(16).toString('hex')}`;
}
return sessionId;
};
// Retry utilities
export interface RetryOptions {
maxAttempts?: number;
baseDelay?: number;
maxDelay?: number;
backoffFactor?: number;
retryCondition?: (error: AppError) => boolean;
}
export const withRetry = async <T>(
operation: () => Promise<T>,
options: RetryOptions = {}
): Promise<T> => {
const {
maxAttempts = 3,
baseDelay = 1000,
maxDelay = 10000,
backoffFactor = 2,
retryCondition = (error: AppError) =>
error.type === ErrorType.NETWORK ||
error.type === ErrorType.SERVER ||
error.code === 'PGRST301', // timeout
} = options;
let lastError: AppError;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await operation();
} catch (error) {
const appError = error instanceof AppError ? error : transformSupabaseError(error);
lastError = appError;
// Don't retry if this is the last attempt or if retry condition is not met
if (attempt === maxAttempts || !retryCondition(appError)) {
throw appError;
}
// Calculate delay with exponential backoff
const delay = Math.min(baseDelay * Math.pow(backoffFactor, attempt - 1), maxDelay);
console.warn(
`Operation failed (attempt ${attempt}/${maxAttempts}). Retrying in ${delay}ms...`,
appError.message
);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw lastError!;
};
// Error boundary helpers for React
export const handleAsyncError = (error: unknown): AppError => {
if (error instanceof AppError) {
return error;
}
return transformSupabaseError(error);
};
// Validation helpers
export const createValidationError = (
field: string,
message: string,
value?: any
): ValidationError => {
return new ValidationError(message, field, 'VALIDATION_FAILED', {
field,
value,
});
};
export const validateRequired = (value: any, fieldName: string): void => {
if (value === null || value === undefined || value === '') {
throw createValidationError(fieldName, `${fieldName} is required`);
}
};
export const validateEmail = (email: string, fieldName = 'email'): void => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw createValidationError(fieldName, 'Invalid email format');
}
};
export const validateMinLength = (value: string, minLength: number, fieldName: string): void => {
if (value.length < minLength) {
throw createValidationError(
fieldName,
`${fieldName} must be at least ${minLength} characters long`
);
}
};
// Export error handling hook for React components
export const useErrorHandler = () => {
return {
handleError: (error: unknown, context?: Record<string, any>) => {
const appError = handleAsyncError(error);
logError(appError, context);
return appError;
},
getUserMessage: (error: unknown): string => {
const appError = handleAsyncError(error);
return getUserFriendlyMessage(appError);
},
transformError: transformSupabaseError,
createValidationError,
validateRequired,
validateEmail,
validateMinLength,
};
};
// Global error handler
export const setupGlobalErrorHandling = (): void => {
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
const error = transformSupabaseError(event.reason);
logError(error, { source: 'unhandledRejection' });
// Prevent the default browser behavior
event.preventDefault();
});
// Handle uncaught errors
window.addEventListener('error', (event) => {
const error = new AppError(
event.message || 'Uncaught error',
ErrorType.UNKNOWN,
ErrorSeverity.HIGH,
undefined,
{
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
}
);
logError(error, { source: 'uncaughtError' });
});
};
// Development helpers
export const simulateError = (type: ErrorType, message?: string): AppError => {
if (import.meta.env.MODE !== 'development') {
throw new Error('simulateError is only available in development mode');
}
const defaultMessages = {
[ErrorType.NETWORK]: 'Simulated network error',
[ErrorType.AUTH]: 'Simulated authentication error',
[ErrorType.VALIDATION]: 'Simulated validation error',
[ErrorType.NOT_FOUND]: 'Simulated not found error',
[ErrorType.PERMISSION_DENIED]: 'Simulated permission error',
[ErrorType.RATE_LIMIT]: 'Simulated rate limit error',
[ErrorType.SERVER]: 'Simulated server error',
[ErrorType.DATABASE]: 'Simulated database error',
[ErrorType.UNKNOWN]: 'Simulated unknown error',
};
return new AppError(
message || defaultMessages[type],
type,
ErrorSeverity.MEDIUM,
'SIMULATED_ERROR'
);
};
|