class APIError extends Error { constructor(status, errorCode, message) { super(message); this.status = status; this.errorCode = errorCode; this.name = 'APIError'; }}async function makeApiCall(endpoint, options = {}) { try { const response = await fetch(endpoint, options); const data = await response.json(); if (!data.status) { throw new APIError( response.status, data.error, data.message || data.error ); } return data.data; } catch (error) { // Handle network errors if (error instanceof TypeError) { throw new APIError(0, 'network_error', 'Unable to connect to API'); } throw error; }}async function handleApiCall(apiFunction) { try { return await apiFunction(); } catch (error) { if (error instanceof APIError) { return handleAPIError(error); } else { console.error('Unexpected error:', error); throw error; } }}function handleAPIError(error) { switch (error.status) { case 401: return handleAuthError(error); case 403: return handleForbiddenError(error); case 404: return handleNotFoundError(error); case 422: return handleValidationError(error); case 429: return handleRateLimitError(error); case 500: return handleServerError(error); default: return handleGenericError(error); }}
Handling Specific Errors
401 - Authentication
403 - Forbidden
404 - Not Found
422 - Validation
429 - Rate Limit
500 - Server Error
async function handleAuthError(error) { console.log('Token expired or invalid'); // 1. Try to refresh token try { await refreshAccessToken(); // 2. Retry the failed request return await retryLastRequest(); } catch (refreshError) { // 3. If refresh fails, redirect to login redirectToLogin(); throw new Error('Authentication failed'); }}async function refreshAccessToken() { const credentials = getStoredCredentials(); const response = await login( credentials.appSecret, credentials.restSecret ); storeAccessToken(response.access_token); return response;}
function handleForbiddenError(error) { if (error.errorCode === 'URL hatalı') { // Invalid UUID or resource ID console.error('Invalid resource ID'); notifyUser('The requested resource ID is invalid'); // Log for debugging logError('Invalid UUID', { endpoint: error.endpoint, resourceId: error.resourceId }); } else { // Insufficient permissions console.error('Access denied'); notifyUser('You do not have permission to access this resource'); }}
function handleNotFoundError(error) { switch (error.errorCode) { case 'sipariş bulunamadı': console.log('Order not found'); notifyUser('Order not found. It may have been canceled.'); break; case 'restoran bulunamadı': console.log('Restaurant not found'); notifyUser('Restaurant not found'); break; case 'ürün bulunamadı': console.log('Food item not found'); notifyUser('Menu item not found'); break; default: notifyUser('The requested resource was not found'); }}
function handleValidationError(error) { console.error('Validation failed:', error.message); // Extract field name from error message const fieldMatch = error.message.match(/(\w+) is required/); const fieldName = fieldMatch ? fieldMatch[1] : 'unknown'; // Highlight error in UI highlightErrorField(fieldName); // Show user-friendly message notifyUser(`Please provide a valid ${fieldName}`); // Log for debugging logValidationError({ field: fieldName, message: error.message, requestData: error.requestData });}
async function handleRateLimitError(error) { console.log('Rate limit exceeded'); // Show user message notifyUser('Too many requests. Please wait 30 seconds.'); // Wait 30 seconds await sleep(30000); // Retry automatically console.log('Retrying request...'); return await retryLastRequest();}function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms));}
async function handleServerError(error, attempt = 1) { const maxRetries = 3; console.error(`Server error (attempt ${attempt}/${maxRetries})`); if (attempt >= maxRetries) { // Give up after max retries notifyUser('Server error. Please try again later.'); logCriticalError('Server error after max retries', error); throw error; } // Exponential backoff: 1s, 2s, 4s const delay = 1000 * Math.pow(2, attempt - 1); console.log(`Waiting ${delay}ms before retry...`); await sleep(delay); // Retry try { return await retryLastRequest(); } catch (retryError) { return handleServerError(retryError, attempt + 1); }}
function getUserMessage(error) { const messages = { 401: 'Your session has expired. Please log in again.', 403: 'You don\'t have permission to perform this action.', 404: 'The requested item was not found.', 422: 'Please check your input and try again.', 429: 'Too many requests. Please wait a moment.', 500: 'Something went wrong. Please try again later.' }; return messages[error.status] || 'An unexpected error occurred. Please try again.';}