-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy patherror-handler.js
More file actions
287 lines (264 loc) · 8.36 KB
/
error-handler.js
File metadata and controls
287 lines (264 loc) · 8.36 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
/**
* ErrorHandler - Context-specific error messages with recovery actions
* Part of User Readiness Week 1, Day 4 Implementation
*/
class ErrorHandler {
constructor() {
this.errorCategories = {
NETWORK: 'network',
AUTH: 'auth',
VALIDATION: 'validation',
NOT_FOUND: 'not_found',
PERMISSION: 'permission',
SERVER: 'server',
QUOTA: 'quota',
UNKNOWN: 'unknown'
};
this.init();
}
init() {
console.log('✅ ErrorHandler initialized');
}
/**
* Categorize error based on error object
* @param {Error|Object} error - Error object or API response
* @returns {string} Error category
*/
categorize(error) {
// Network errors
if (error.message?.includes('Failed to fetch') ||
error.message?.includes('Network request failed') ||
error.name === 'NetworkError' ||
!navigator.onLine) {
return this.errorCategories.NETWORK;
}
// Auth errors
if (error.status === 401 ||
error.code === 'UNAUTHORIZED' ||
error.message?.includes('unauthorized') ||
error.message?.includes('session expired')) {
return this.errorCategories.AUTH;
}
// Validation errors
if (error.status === 400 ||
error.code === 'VALIDATION_ERROR' ||
error.message?.includes('validation') ||
error.message?.includes('invalid')) {
return this.errorCategories.VALIDATION;
}
// Not found errors
if (error.status === 404 ||
error.code === 'NOT_FOUND' ||
error.message?.includes('not found')) {
return this.errorCategories.NOT_FOUND;
}
// Permission errors
if (error.status === 403 ||
error.code === 'FORBIDDEN' ||
error.message?.includes('permission') ||
error.message?.includes('forbidden')) {
return this.errorCategories.PERMISSION;
}
// Quota/limit errors
if (error.status === 429 ||
error.code === 'QUOTA_EXCEEDED' ||
error.message?.includes('quota') ||
error.message?.includes('limit exceeded')) {
return this.errorCategories.QUOTA;
}
// Server errors
if (error.status >= 500 ||
error.code === 'SERVER_ERROR' ||
error.message?.includes('server error')) {
return this.errorCategories.SERVER;
}
return this.errorCategories.UNKNOWN;
}
/**
* Get context-specific error message and recovery action
* @param {Error|Object} error - Error object
* @param {string} context - Operation context (e.g., 'load_groups', 'create_group')
* @returns {Object} { message, action, duration }
*/
getContextualError(error, context) {
const category = this.categorize(error);
const contextKey = `${context}_${category}`;
// Context-specific error messages with recovery actions
const errorMessages = {
// Load Groups errors
'load_groups_network': {
message: 'No se pueden cargar los grupos. Por favor verifica tu conexión a internet.',
action: {
text: 'Reintentar',
onClick: () => window.advancedGroupsSystem?.loadGroupsContent(true)
},
duration: 8000
},
'load_groups_auth': {
message: 'Tu sesión ha expirado. Por favor inicia sesión nuevamente.',
action: {
text: 'Iniciar Sesión',
onClick: () => window.location.href = '/auth.html'
},
duration: 10000
},
'load_groups_server': {
message: 'Error del servidor al cargar grupos. Nuestro equipo ha sido notificado.',
action: {
text: 'Reintentar',
onClick: () => window.advancedGroupsSystem?.loadGroupsContent(true)
},
duration: 8000
},
'load_groups_unknown': {
message: 'Error al cargar grupos. Por favor intenta de nuevo.',
action: {
text: 'Reintentar',
onClick: () => window.advancedGroupsSystem?.loadGroupsContent(true)
},
duration: 6000
},
// Create Group errors
'create_group_network': {
message: 'No se pudo crear el grupo. Verifica tu conexión a internet.',
action: {
text: 'Reintentar',
onClick: () => {
const form = document.getElementById('createGroupForm');
if (form) {
const event = new Event('submit', { bubbles: true, cancelable: true });
form.dispatchEvent(event);
}
}
},
duration: 8000
},
'create_group_validation': {
message: error.message || 'Datos del grupo inválidos. Por favor revisa el formulario.',
action: null,
duration: 6000
},
'create_group_quota': {
message: 'Has alcanzado el límite de grupos. Actualiza tu plan para crear más grupos.',
action: {
text: 'Ver Planes',
onClick: () => window.location.href = '/pricing.html'
},
duration: 10000
},
'create_group_auth': {
message: 'Tu sesión ha expirado. Por favor inicia sesión e intenta de nuevo.',
action: {
text: 'Iniciar Sesión',
onClick: () => window.location.href = '/auth.html'
},
duration: 10000
},
'create_group_server': {
message: 'Error del servidor al crear grupo. Por favor intenta más tarde.',
action: {
text: 'Reintentar',
onClick: () => {
const form = document.getElementById('createGroupForm');
if (form) {
const event = new Event('submit', { bubbles: true, cancelable: true });
form.dispatchEvent(event);
}
}
},
duration: 8000
},
'create_group_unknown': {
message: 'Error al crear grupo: ' + (error.message || 'Error desconocido'),
action: null,
duration: 6000
},
// API Request errors
'api_request_network': {
message: 'Sin conexión. Verifica tu conexión a internet e intenta de nuevo.',
action: null,
duration: 6000
},
'api_request_auth': {
message: 'Sesión expirada. Por favor inicia sesión nuevamente.',
action: {
text: 'Iniciar Sesión',
onClick: () => window.location.href = '/auth.html'
},
duration: 10000
},
'api_request_server': {
message: 'El servidor no responde. Por favor intenta más tarde.',
action: null,
duration: 6000
},
// Update Group errors
'update_group_permission': {
message: 'No tienes permiso para modificar este grupo.',
action: null,
duration: 6000
},
'update_group_not_found': {
message: 'Grupo no encontrado. Puede haber sido eliminado.',
action: {
text: 'Actualizar Lista',
onClick: () => window.advancedGroupsSystem?.loadGroupsContent(true)
},
duration: 8000
}
};
// Return context-specific error or generic fallback
return errorMessages[contextKey] || {
message: error.message || 'Ha ocurrido un error. Por favor intenta de nuevo.',
action: null,
duration: 5000
};
}
/**
* Handle error with context-specific message and action
* @param {Error|Object} error - Error object
* @param {string} context - Operation context
*/
handle(error, context) {
const { message, action, duration } = this.getContextualError(error, context);
// Show error with toast system
if (window.showError) {
window.showError(message, duration, { action });
} else {
console.error(`[${context}]`, message, error);
alert(message);
}
// Log to console for debugging
console.error(`❌ Error [${context}]:`, {
category: this.categorize(error),
originalError: error,
message: message
});
}
/**
* Check if user is online
* @returns {boolean}
*/
isOnline() {
return navigator.onLine;
}
/**
* Wrap async function with error handling
* @param {Function} fn - Async function to wrap
* @param {string} context - Operation context
* @returns {Function} Wrapped function
*/
wrap(fn, context) {
return async (...args) => {
try {
return await fn(...args);
} catch (error) {
this.handle(error, context);
throw error;
}
};
}
}
// Initialize global instance
window.errorHandler = new ErrorHandler();
console.log('✅ ErrorHandler loaded and available globally');