-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathairtable-error-logger.ts
More file actions
659 lines (567 loc) · 18.4 KB
/
Copy pathairtable-error-logger.ts
File metadata and controls
659 lines (567 loc) · 18.4 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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/**
* Comprehensive Error Logging for Airtable Field Mapping Issues
*
* This module provides specialized logging for Airtable API errors with detailed
* context about field mappings, base IDs, and API responses to help debug
* field mapping issues and base ID problems.
*/
import { ErrorContext, ErrorSeverity, createDataFetchingError, type EnhancedError } from "@/lib/error-handling";
import { LogLevel, logger } from "@/lib/logging";
import { validateBaseId } from "./airtable-constants";
// === Airtable-specific Error Types ===
export enum AirtableErrorType {
FIELD_MAPPING = 'FIELD_MAPPING',
BASE_ID_INVALID = 'BASE_ID_INVALID',
BASE_ID_ACCESS = 'BASE_ID_ACCESS',
AUTHENTICATION = 'AUTHENTICATION',
RATE_LIMIT = 'RATE_LIMIT',
NETWORK = 'NETWORK',
UNKNOWN_FIELD = 'UNKNOWN_FIELD',
PERMISSION_DENIED = 'PERMISSION_DENIED',
RECORD_NOT_FOUND = 'RECORD_NOT_FOUND',
VALIDATION_ERROR = 'VALIDATION_ERROR'
}
export interface AirtableErrorContext {
baseId?: string;
tableName?: string;
recordId?: string;
requestedFields?: string[];
validFields?: string[];
invalidFields?: string[];
fieldSuggestions?: Record<string, string>;
apiUrl?: string;
httpStatus?: number;
responseBody?: string;
requestParams?: Record<string, any>;
contentType?: string;
operation?: string;
retryAttempt?: number;
timestamp: number;
}
export interface AirtableError extends EnhancedError {
airtableErrorType: AirtableErrorType;
airtableContext: AirtableErrorContext;
}
// === Error Detection Functions ===
export function detectAirtableErrorType(error: Error, response?: Response): AirtableErrorType {
const message = error.message.toLowerCase();
const status = response?.status;
// Field mapping errors (422 with UNKNOWN_FIELD_NAME)
if (status === 422 && message.includes('unknown_field_name')) {
return AirtableErrorType.UNKNOWN_FIELD;
}
// Base ID validation errors
if (message.includes('invalid base id') || message.includes('base id format')) {
return AirtableErrorType.BASE_ID_INVALID;
}
// Base access errors (404 for base not found)
if (status === 404 && message.includes('base')) {
return AirtableErrorType.BASE_ID_ACCESS;
}
// Authentication errors
if (status === 401 || message.includes('unauthorized') || message.includes('authentication')) {
return AirtableErrorType.AUTHENTICATION;
}
// Rate limiting
if (status === 429 || message.includes('rate limit')) {
return AirtableErrorType.RATE_LIMIT;
}
// Permission errors
if (status === 403 || message.includes('permission') || message.includes('forbidden')) {
return AirtableErrorType.PERMISSION_DENIED;
}
// Record not found
if (status === 404 && message.includes('record')) {
return AirtableErrorType.RECORD_NOT_FOUND;
}
// Validation errors
if (status === 400 || message.includes('validation')) {
return AirtableErrorType.VALIDATION_ERROR;
}
// Network errors
if (message.includes('fetch') || message.includes('network') || message.includes('timeout')) {
return AirtableErrorType.NETWORK;
}
// Default to field mapping if we can't determine
return AirtableErrorType.FIELD_MAPPING;
}
export function extractFieldNamesFromError(errorMessage: string): string[] {
const fieldMatches = errorMessage.match(/field\s+"([^"]+)"/gi);
if (!fieldMatches) return [];
return fieldMatches.map(match => {
const fieldName = match.match(/field\s+"([^"]+)"/i);
return fieldName ? fieldName[1] : '';
}).filter(Boolean);
}
export function parseAirtableErrorResponse(responseBody: string): {
errorType?: string;
errorMessage?: string;
invalidFields?: string[];
details?: any;
} {
try {
const parsed = JSON.parse(responseBody);
if (parsed.error) {
return {
errorType: parsed.error.type,
errorMessage: parsed.error.message,
invalidFields: extractFieldNamesFromError(parsed.error.message),
details: parsed.error
};
}
return { details: parsed };
} catch {
// If JSON parsing fails, try to extract field names from raw text
return {
invalidFields: extractFieldNamesFromError(responseBody),
errorMessage: responseBody
};
}
}
// === Error Creation Functions ===
export function createAirtableError(
message: string,
errorType: AirtableErrorType,
context: Partial<AirtableErrorContext>,
originalError?: Error,
response?: Response
): AirtableError {
const severity = getErrorSeverity(errorType);
const userMessage = getUserFriendlyMessage(errorType);
const enhancedError = createDataFetchingError(
message,
ErrorContext.API_ROUTE,
{
severity,
userMessage,
code: errorType,
statusCode: response?.status,
retryable: isRetryableError(errorType),
debugInfo: {
originalError: originalError?.message,
originalStack: originalError?.stack
}
}
) as AirtableError;
enhancedError.airtableErrorType = errorType;
enhancedError.airtableContext = {
timestamp: Date.now(),
...context
};
return enhancedError;
}
export function createFieldMappingError(
tableName: string,
invalidFields: string[],
context: Partial<AirtableErrorContext> = {}
): AirtableError {
const message = `Field mapping error in table "${tableName}": Unknown fields [${invalidFields.join(', ')}]`;
return createAirtableError(
message,
AirtableErrorType.UNKNOWN_FIELD,
{
tableName,
invalidFields,
operation: 'field_validation',
...context
}
);
}
export function createBaseIdError(
baseId: string,
tableName?: string,
context: Partial<AirtableErrorContext> = {}
): AirtableError {
const isValidFormat = validateBaseId(baseId);
const errorType = isValidFormat ? AirtableErrorType.BASE_ID_ACCESS : AirtableErrorType.BASE_ID_INVALID;
const message = isValidFormat
? `Cannot access Airtable base "${baseId}"${tableName ? ` for table "${tableName}"` : ''}`
: `Invalid Airtable base ID format: "${baseId}". Expected format: app + 14 alphanumeric characters`;
return createAirtableError(
message,
errorType,
{
baseId,
tableName,
operation: 'base_validation',
...context
}
);
}
// === Error Severity and User Messages ===
function getErrorSeverity(errorType: AirtableErrorType): ErrorSeverity {
switch (errorType) {
case AirtableErrorType.BASE_ID_INVALID:
case AirtableErrorType.AUTHENTICATION:
return ErrorSeverity.CRITICAL;
case AirtableErrorType.UNKNOWN_FIELD:
case AirtableErrorType.BASE_ID_ACCESS:
case AirtableErrorType.PERMISSION_DENIED:
return ErrorSeverity.HIGH;
case AirtableErrorType.RATE_LIMIT:
case AirtableErrorType.VALIDATION_ERROR:
return ErrorSeverity.MEDIUM;
case AirtableErrorType.RECORD_NOT_FOUND:
case AirtableErrorType.NETWORK:
return ErrorSeverity.LOW;
default:
return ErrorSeverity.MEDIUM;
}
}
function getUserFriendlyMessage(errorType: AirtableErrorType): string {
switch (errorType) {
case AirtableErrorType.UNKNOWN_FIELD:
return "ڈیٹا فیلڈ کی خرابی، براہ کرم دوبارہ کوشش کریں۔";
case AirtableErrorType.BASE_ID_INVALID:
case AirtableErrorType.BASE_ID_ACCESS:
return "ڈیٹابیس کنکشن کی خرابی، براہ کرم بعد میں کوشش کریں۔";
case AirtableErrorType.AUTHENTICATION:
return "اجازت کی خرابی، براہ کرم دوبارہ لاگ ان کریں۔";
case AirtableErrorType.RATE_LIMIT:
return "بہت زیادہ درخواستیں، براہ کرم کچھ دیر انتظار کریں۔";
case AirtableErrorType.PERMISSION_DENIED:
return "اس ڈیٹا تک رسائی کی اجازت نہیں ہے۔";
case AirtableErrorType.RECORD_NOT_FOUND:
return "یہ ڈیٹا دستیاب نہیں ہے۔";
case AirtableErrorType.NETWORK:
return "انٹرنیٹ کنکشن کی خرابی، براہ کرم دوبارہ کوشش کریں۔";
default:
return "ڈیٹا لوڈ کرنے میں خرابی، براہ کرم دوبارہ کوشش کریں۔";
}
}
function isRetryableError(errorType: AirtableErrorType): boolean {
switch (errorType) {
case AirtableErrorType.RATE_LIMIT:
case AirtableErrorType.NETWORK:
return true;
case AirtableErrorType.BASE_ID_INVALID:
case AirtableErrorType.AUTHENTICATION:
case AirtableErrorType.PERMISSION_DENIED:
case AirtableErrorType.UNKNOWN_FIELD:
return false;
default:
return true;
}
}
// === Logging Functions ===
export class AirtableErrorLogger {
private static instance: AirtableErrorLogger;
private errorCounts: Map<string, number> = new Map();
private lastErrors: Map<string, AirtableError> = new Map();
static getInstance(): AirtableErrorLogger {
if (!AirtableErrorLogger.instance) {
AirtableErrorLogger.instance = new AirtableErrorLogger();
}
return AirtableErrorLogger.instance;
}
/**
* Log an Airtable error with comprehensive context
*/
logAirtableError(error: AirtableError): void {
const context = error.airtableContext;
const errorKey = this.getErrorKey(error);
// Track error frequency
const count = (this.errorCounts.get(errorKey) || 0) + 1;
this.errorCounts.set(errorKey, count);
this.lastErrors.set(errorKey, error);
// Log with appropriate level based on severity
const logLevel = this.getLogLevel(error.severity);
const logContext = 'AIRTABLE_ERROR';
// Create detailed log message
const logMessage = this.formatErrorMessage(error, count);
// Create comprehensive log data
const logData = {
errorType: error.airtableErrorType,
errorCount: count,
baseId: context.baseId,
tableName: context.tableName,
contentType: context.contentType,
operation: context.operation,
httpStatus: context.httpStatus,
requestedFields: context.requestedFields,
invalidFields: context.invalidFields,
fieldSuggestions: context.fieldSuggestions,
apiUrl: context.apiUrl,
retryAttempt: context.retryAttempt,
isRetryable: error.retryable,
timestamp: new Date(context.timestamp).toISOString()
};
// Log using the enhanced logger
switch (logLevel) {
case LogLevel.DEBUG:
logger.debug(logContext, logMessage, logData);
break;
case LogLevel.INFO:
logger.info(logContext, logMessage, logData);
break;
case LogLevel.WARN:
logger.warn(logContext, logMessage, logData);
break;
case LogLevel.ERROR:
logger.error(logContext, logMessage, error, logData);
break;
case LogLevel.CRITICAL:
logger.critical(logContext, logMessage, error, logData);
break;
}
// Log field mapping details if available
if (error.airtableErrorType === AirtableErrorType.UNKNOWN_FIELD && context.invalidFields?.length) {
this.logFieldMappingDetails(context);
}
// Log base ID validation details
if (error.airtableErrorType === AirtableErrorType.BASE_ID_INVALID ||
error.airtableErrorType === AirtableErrorType.BASE_ID_ACCESS) {
this.logBaseIdDetails(context);
}
}
/**
* Log field mapping validation results
*/
logFieldValidation(
tableName: string,
contentType: string,
requestedFields: string[],
validFields: string[],
invalidFields: string[],
corrections: Record<string, string>
): void {
const hasErrors = invalidFields.length > 0;
const hasCorrections = Object.keys(corrections).length > 0;
if (hasErrors || hasCorrections) {
const message = `Field validation for ${tableName} (${contentType})`;
const logLevel = hasErrors ? LogLevel.WARN : LogLevel.INFO;
if (logLevel === LogLevel.WARN) {
logger.warn('FIELD_VALIDATION', message, {
tableName,
contentType,
requestedFields,
validFields,
invalidFields,
corrections,
validationResult: hasErrors ? 'failed' : 'success_with_corrections'
});
} else {
logger.info('FIELD_VALIDATION', message, {
tableName,
contentType,
requestedFields,
validFields,
invalidFields,
corrections,
validationResult: hasErrors ? 'failed' : 'success_with_corrections'
});
}
}
}
/**
* Log base ID usage and validation
*/
logBaseIdUsage(
baseId: string,
tableName: string,
operation: string,
success: boolean,
details?: any
): void {
const message = `Base ID usage: ${baseId} for ${tableName} (${operation}) - ${success ? 'success' : 'failed'}`;
const logLevel = success ? LogLevel.DEBUG : LogLevel.ERROR;
if (logLevel === LogLevel.DEBUG) {
logger.debug('BASE_ID_USAGE', message, {
baseId,
tableName,
operation,
success,
isValidFormat: validateBaseId(baseId),
details
});
} else {
logger.error('BASE_ID_USAGE', message, undefined, {
baseId,
tableName,
operation,
success,
isValidFormat: validateBaseId(baseId),
details
});
}
}
/**
* Log API request details for debugging
*/
logApiRequest(
method: string,
url: string,
params: any,
response?: Response,
error?: Error
): void {
const isStarted = !response && !error;
const success = !error && !!response?.ok;
const message = `Airtable API ${method} ${url} - ${
isStarted ? "started" : success ? "success" : "failed"
}`;
const logLevel =
error || (response && !response.ok) ? LogLevel.ERROR : LogLevel.DEBUG;
if (logLevel === LogLevel.DEBUG) {
logger.debug('AIRTABLE_API', message, {
method,
url,
params,
status: response?.status,
statusText: response?.statusText,
error: error?.message,
success: isStarted ? undefined : success
});
} else {
logger.error('AIRTABLE_API', message, error ? error as EnhancedError : undefined, {
method,
url,
params,
status: response?.status,
statusText: response?.statusText,
error: error?.message,
success
});
}
}
// === Private Helper Methods ===
private getErrorKey(error: AirtableError): string {
const context = error.airtableContext;
return `${error.airtableErrorType}:${context.baseId}:${context.tableName}:${context.invalidFields?.join(',')}`;
}
private getLogLevel(severity: ErrorSeverity): LogLevel {
switch (severity) {
case ErrorSeverity.CRITICAL:
return LogLevel.CRITICAL;
case ErrorSeverity.HIGH:
return LogLevel.ERROR;
case ErrorSeverity.MEDIUM:
return LogLevel.WARN;
case ErrorSeverity.LOW:
return LogLevel.INFO;
default:
return LogLevel.ERROR;
}
}
private formatErrorMessage(error: AirtableError, count: number): string {
const context = error.airtableContext;
const countSuffix = count > 1 ? ` (occurred ${count} times)` : '';
return `${error.airtableErrorType}: ${error.message}${countSuffix}`;
}
private logFieldMappingDetails(context: AirtableErrorContext): void {
if (!context.invalidFields?.length) return;
logger.warn('FIELD_MAPPING_DETAILS', 'Invalid field mapping detected', {
tableName: context.tableName,
contentType: context.contentType,
invalidFields: context.invalidFields,
suggestions: context.fieldSuggestions,
requestedFields: context.requestedFields,
validFields: context.validFields
});
}
private logBaseIdDetails(context: AirtableErrorContext): void {
if (!context.baseId) return;
const isValidFormat = validateBaseId(context.baseId);
logger.error('BASE_ID_DETAILS', 'Base ID validation failed', undefined, {
baseId: context.baseId,
tableName: context.tableName,
isValidFormat,
expectedFormat: 'app + 14 alphanumeric characters',
actualLength: context.baseId.length,
startsWithApp: context.baseId.startsWith('app')
});
}
}
// === Convenience Functions ===
export const airtableErrorLogger = AirtableErrorLogger.getInstance();
export function logAirtableError(error: AirtableError): void {
airtableErrorLogger.logAirtableError(error);
}
export function logFieldValidation(
tableName: string,
contentType: string,
requestedFields: string[],
validFields: string[],
invalidFields: string[],
corrections: Record<string, string>
): void {
airtableErrorLogger.logFieldValidation(
tableName,
contentType,
requestedFields,
validFields,
invalidFields,
corrections
);
}
export function logBaseIdUsage(
baseId: string,
tableName: string,
operation: string,
success: boolean,
details?: any
): void {
airtableErrorLogger.logBaseIdUsage(baseId, tableName, operation, success, details);
}
export function logApiRequest(
method: string,
url: string,
params: any,
response?: Response,
error?: Error
): void {
airtableErrorLogger.logApiRequest(method, url, params, response, error);
}
// === Error Handling Wrapper ===
/**
* Wrap Airtable API calls with comprehensive error logging
*/
export async function withAirtableErrorLogging<T>(
operation: string,
context: Partial<AirtableErrorContext>,
apiCall: () => Promise<T>
): Promise<T> {
const startTime = Date.now();
try {
const result = await apiCall();
// Log successful operation
if (context.baseId && context.tableName) {
logBaseIdUsage(context.baseId, context.tableName, operation, true, {
duration: Date.now() - startTime
});
}
return result;
} catch (error) {
const duration = Date.now() - startTime;
// Create and log Airtable error
const airtableError = error instanceof Error
? createAirtableError(
`${operation} failed: ${error.message}`,
detectAirtableErrorType(error),
{
...context,
operation,
timestamp: startTime
},
error
)
: createAirtableError(
`${operation} failed with unknown error`,
AirtableErrorType.FIELD_MAPPING,
{
...context,
operation,
timestamp: startTime
}
);
logAirtableError(airtableError);
// Log failed base ID usage
if (context.baseId && context.tableName) {
logBaseIdUsage(context.baseId, context.tableName, operation, false, {
duration,
error: error instanceof Error ? error.message : String(error)
});
}
throw airtableError;
}
}