File size: 5,604 Bytes
70429fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// error-handler.service.ts (YENİ DOSYA)
// Path: /flare-ui/src/app/services/error-handler.service.ts

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';

interface FlareError {
  error: string;
  message: string;
  details?: any;
  request_id?: string;
  timestamp?: string;
  user_action?: string;
}

@Injectable({
  providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
  constructor(private injector: Injector) {}

  handleError(error: Error | HttpErrorResponse): void {
    // Get services lazily to avoid circular dependency
    const snackBar = this.injector.get(MatSnackBar);
    const router = this.injector.get(Router);
    
    console.error('Global error caught:', error);
    
    // Handle HTTP errors
    if (error instanceof HttpErrorResponse) {
      this.handleHttpError(error, snackBar, router);
    } else {
      // Handle client-side errors
      this.handleClientError(error, snackBar);
    }
  }
  
  private handleHttpError(error: HttpErrorResponse, snackBar: MatSnackBar, router: Router): void {
    const flareError = error.error as FlareError;
    
    // Race condition error (409)
    if (error.status === 409 && flareError.error === 'RaceConditionError') {
      const snackBarRef = snackBar.open(
        flareError.message || 'The data was modified by another user. Please refresh and try again.',
        'Refresh',
        {
          duration: 0,
          panelClass: ['error-snackbar', 'race-condition-snackbar']
        }
      );
      
      snackBarRef.onAction().subscribe(() => {
        window.location.reload();
      });
      
      // Show additional info if available
      if (flareError.details?.last_update_user) {
        console.info(`Last updated by: ${flareError.details.last_update_user} at ${flareError.details.last_update_date}`);
      }
      return;
    }
    
    // Authentication error (401)
    if (error.status === 401) {
      snackBar.open(
        'Your session has expired. Please login again.',
        'Login',
        {
          duration: 5000,
          panelClass: ['error-snackbar']
        }
      ).onAction().subscribe(() => {
        router.navigate(['/login']);
      });
      return;
    }
    
    // Validation error (422)
    if (error.status === 422 && flareError.details) {
      const fieldErrors = flareError.details
        .map((d: any) => `${d.field}: ${d.message}`)
        .join('\n');
      
      snackBar.open(
        flareError.message || 'Validation failed. Please check your input.',
        'Close',
        {
          duration: 8000,
          panelClass: ['error-snackbar', 'validation-snackbar']
        }
      );
      
      console.error('Validation errors:', flareError.details);
      return;
    }
    
    // Not found error (404)
    if (error.status === 404) {
      snackBar.open(
        flareError.message || 'The requested resource was not found.',
        'Close',
        {
          duration: 5000,
          panelClass: ['error-snackbar']
        }
      );
      return;
    }
    
    // Server errors (5xx)
    if (error.status >= 500) {
      const message = flareError.message || 'A server error occurred. Please try again later.';
      const requestId = flareError.request_id;
      
      snackBar.open(
        requestId ? `${message} (Request ID: ${requestId})` : message,
        'Close',
        {
          duration: 8000,
          panelClass: ['error-snackbar', 'server-error-snackbar']
        }
      );
      return;
    }
    
    // Generic HTTP error
    snackBar.open(
      flareError.message || `HTTP Error ${error.status}: ${error.statusText}`,
      'Close',
      {
        duration: 6000,
        panelClass: ['error-snackbar']
      }
    );
  }
  
  private handleClientError(error: Error, snackBar: MatSnackBar): void {
    // Check if it's a network error
    if (error.message.includes('NetworkError') || error.message.includes('Failed to fetch')) {
      snackBar.open(
        'Network connection error. Please check your internet connection.',
        'Retry',
        {
          duration: 0,
          panelClass: ['error-snackbar', 'network-error-snackbar']
        }
      ).onAction().subscribe(() => {
        window.location.reload();
      });
      return;
    }
    
    // Generic client error
    snackBar.open(
      'An unexpected error occurred. Please refresh the page.',
      'Refresh',
      {
        duration: 6000,
        panelClass: ['error-snackbar']
      }
    ).onAction().subscribe(() => {
      window.location.reload();
    });
  }
}

// Error interceptor for consistent error format
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        // Log request details for debugging
        console.error('HTTP Error:', {
          url: req.url,
          method: req.method,
          status: error.status,
          error: error.error,
          requestId: error.headers.get('X-Request-ID')
        });
        
        // Re-throw to be handled by global error handler
        return throwError(() => error);
      })
    );
  }
}