Skip to content

Improve error handling across async operations and fix build error#1

Draft
Copilot wants to merge 3 commits intomainfrom
copilot/improve-error-handling
Draft

Improve error handling across async operations and fix build error#1
Copilot wants to merge 3 commits intomainfrom
copilot/improve-error-handling

Conversation

Copy link
Copy Markdown

Copilot AI commented Oct 23, 2025

Overview

This PR implements comprehensive error handling improvements across the application's async operations, addressing missing error handling in critical paths and improving debugging capabilities.

Problem

The application had several async operations that lacked proper error handling:

  1. OpenAI API client - No validation of HTTP responses or error handling for failed requests
  2. WebSocket operations - Missing error handlers for connection failures and message parsing
  3. Firestore operations - Delete and update operations had no error handling
  4. AI flows - No validation of empty outputs or error handling for model failures
  5. PDF generation - No error handling for generation failures
  6. Build error - Duplicate (app/expenses directory with typo was breaking builds

Changes Made

1. OpenAI Responses Client (src/lib/openai-responses-client.ts)

Added comprehensive error handling to all async methods:

// Before
async createResponse(params: CreateResponseParams) {
  const response = await fetch(`${this.baseURL}/responses`, {...})
  return response.json()
}

// After
async createResponse(params: CreateResponseParams) {
  try {
    const response = await fetch(`${this.baseURL}/responses`, {...})
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(`API request failed: ${response.status} ${response.statusText}`)
    }
    return response.json()
  } catch (error) {
    console.error('Error creating response:', error)
    throw error
  }
}
  • HTTP response validation with descriptive error messages
  • Error logging before re-throwing
  • WebSocket error handling for connection failures and message parsing
  • Added onclose event handler and connection state warnings

2. Firestore Operations (src/app/(app)/layout.tsx)

Added try-catch blocks to data mutation operations:

const deleteRevenueRecord = useCallback(async (id: string) => {
  try {
    await deleteDoc(doc(db, 'revenue', id));
  } catch (error) {
    console.error('Error deleting revenue record:', error);
    throw error;
  }
}, []);

Similar improvements for deleteExpense() and updateRequestStatus().

3. Enhanced Error Messages (src/lib/actions.ts)

Improved error messages to include actual error details while preserving Arabic user-facing messages:

catch (error) {
  console.error('Error generating financial summary:', error);
  const errorMessage = error instanceof Error ? error.message : 'حدث خطأ غير معروف';
  return {
    success: false,
    message: `حدث خطأ أثناء إنشاء الملخص: ${errorMessage}. الرجاء المحاولة مرة أخرى.`
  };
}

4. PDF Service (src/services/pdf.service.ts)

  • Added error handling to generatePDF() with descriptive error messages
  • Graceful degradation for logo loading failures (optional feature)

5. AI Financial Summary Flow (src/ai/flows/financial-summary.ts)

  • Added error handling to flow wrapper function
  • Validation that AI output is not empty before returning
  • Error logging at both flow and wrapper levels

6. Form Submission (src/components/revenue/revenue-form.tsx)

Added try-catch to form submission handler to prevent unhandled promise rejections.

7. Build Fix

Removed duplicate src/app/(app/expenses/page.tsx directory that was causing webpack build errors due to incorrect import path.

Benefits

  • Better debugging: All errors are logged with context before being handled or thrown
  • Improved reliability: Application gracefully handles network failures, API errors, and invalid data
  • Better user experience: Errors can be properly caught and displayed to users with appropriate messages
  • Maintainability: Consistent error handling patterns across the codebase make future changes easier
  • Build stability: Fixed build error caused by duplicate directory

Testing

The changes have been verified to:

  • ✅ Compile successfully with TypeScript
  • ✅ Not introduce new TypeScript errors
  • ✅ Build without syntax or import errors
  • ✅ Follow existing code patterns and conventions

Error Handling Patterns Used

  1. Try-Catch-Log-Throw: For operations that should propagate errors upstream
  2. HTTP Response Validation: Check response.ok before processing
  3. Graceful Degradation: Optional features fail without breaking core functionality
  4. Informative Error Messages: Include operation context and status codes
Original prompt

H


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 2 commits October 23, 2025 15:20
Co-authored-by: llu77 <163984217+llu77@users.noreply.github.com>
…errors

Co-authored-by: llu77 <163984217+llu77@users.noreply.github.com>
Copilot AI changed the title [WIP] Improve error handling for user inputs Improve error handling across async operations and fix build error Oct 23, 2025
Copilot AI requested a review from llu77 October 23, 2025 15:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants