Spaces:
Building
Building
File size: 9,393 Bytes
9f79da5 4e8cf3c |
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 |
// error-handler.service.ts
// 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 {
try {
// 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);
}
} catch (handlerError) {
// Fallback if error handler itself fails
console.error('Error in error handler:', handlerError);
console.error('Original error:', error);
}
}
private handleHttpError(error: HttpErrorResponse, snackBar: MatSnackBar, router: Router): void {
try {
const flareError = error.error as FlareError;
// Race condition error (409)
if (error.status === 409) {
const isRaceCondition = flareError?.error === 'RaceConditionError' ||
error.error?.type === 'race_condition';
if (isRaceCondition) {
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 = Array.isArray(flareError.details)
? flareError.details.map((d: any) => `${d.field}: ${d.message}`).join('\n')
: 'Validation error occurred';
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 || error.headers?.get('X-Request-ID');
snackBar.open(
requestId ? `${message} (Request ID: ${requestId})` : message,
'Close',
{
duration: 8000,
panelClass: ['error-snackbar', 'server-error-snackbar']
}
);
return;
}
// Network error (0 status usually indicates network issues)
if (error.status === 0) {
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 HTTP error
const errorMessage = flareError?.message || error.message || `HTTP Error ${error.status}: ${error.statusText}`;
snackBar.open(
errorMessage,
'Close',
{
duration: 6000,
panelClass: ['error-snackbar']
}
);
} catch (err) {
console.error('Error in handleHttpError:', err);
this.showGenericError(snackBar);
}
}
private handleClientError(error: Error, snackBar: MatSnackBar): void {
try {
// 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;
}
// Check for specific Angular errors
if (error.name === 'HttpErrorResponse') {
// This might be an HTTP error that wasn't caught properly
this.handleHttpError(error as any, snackBar, this.injector.get(Router));
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();
});
} catch (err) {
console.error('Error in handleClientError:', err);
this.showGenericError(snackBar);
}
}
private showGenericError(snackBar: MatSnackBar): void {
snackBar.open(
'An error occurred. Please try again.',
'Close',
{
duration: 5000,
panelClass: ['error-snackbar']
}
);
}
}
// Error interceptor for consistent error format
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, finalize } from 'rxjs/operators';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
private activeRequests = new Map<string, AbortController>();
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Create abort controller for request cancellation
const requestId = this.generateRequestId();
const abortController = new AbortController();
this.activeRequests.set(requestId, abortController);
// Clone request with additional headers
const clonedReq = req.clone({
setHeaders: {
'X-Request-ID': requestId
}
});
return next.handle(clonedReq).pipe(
catchError((error: HttpErrorResponse) => {
// Log request details for debugging
console.error('HTTP Error:', {
url: req.url,
method: req.method,
status: error.status,
statusText: error.statusText,
error: error.error,
requestId: requestId,
headers: error.headers?.keys()
});
// Enhanced error object
const enhancedError = {
...error,
requestId: requestId,
timestamp: new Date().toISOString(),
url: req.url,
method: req.method
};
// Re-throw to be handled by global error handler
return throwError(() => enhancedError);
}),
finalize(() => {
// Clean up abort controller
this.activeRequests.delete(requestId);
})
);
}
private generateRequestId(): string {
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
// Method to cancel a specific request
cancelRequest(requestId: string): void {
const controller = this.activeRequests.get(requestId);
if (controller) {
controller.abort();
this.activeRequests.delete(requestId);
}
}
// Method to cancel all active requests
cancelAllRequests(): void {
this.activeRequests.forEach((controller) => {
controller.abort();
});
this.activeRequests.clear();
}
} |