-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy patherror-handling.interceptor.ts
97 lines (89 loc) · 3.24 KB
/
error-handling.interceptor.ts
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
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
HttpErrorResponse,
HttpResponse,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { NotificationService } from '../services/notification.service';
import { UiMessage } from '../models/notification';
import { RaidenService } from '../services/raiden.service';
import { RaidenConfig } from 'app/services/raiden.config';
@Injectable()
export class ErrorHandlingInterceptor implements HttpInterceptor {
constructor(
private notificationService: NotificationService,
private raidenService: RaidenService,
private raidenConfig: RaidenConfig
) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap((event) => {
if (
event instanceof HttpResponse &&
event.url.startsWith(this.raidenConfig.api) &&
this.notificationService.apiError
) {
this.raidenService.attemptRpcConnection();
this.raidenService.reconnectSuccessful();
this.notificationService.apiError = undefined;
}
}),
catchError((error) => this.handleError(error))
);
}
private handleError(error: HttpErrorResponse | Error) {
let errMsg: string;
if (
error instanceof HttpErrorResponse &&
error.url.startsWith(this.raidenConfig.api) &&
(error.status === 504 || error.status === 0)
) {
errMsg = 'Could not connect to the Raiden API';
if (
!this.notificationService.apiError ||
this.notificationService.apiError.retrying
) {
this.notificationService.apiError = error;
console.error(`${errMsg}: ${error.message}`);
const notificationMessage: UiMessage = {
title: 'API',
description: 'connection failure',
icon: 'error-mark',
};
this.notificationService.addErrorNotification(
notificationMessage
);
}
return throwError(errMsg);
} else if (error instanceof HttpErrorResponse && error.error.errors) {
const errors = error.error.errors;
if (typeof errors === 'string') {
errMsg = errors;
} else if (typeof errors === 'object') {
errMsg = '';
for (const key in errors) {
if (errors.hasOwnProperty(key)) {
if (errMsg !== '') {
errMsg += '\n';
}
errMsg += `${errors[key]}`;
}
}
} else {
errMsg = errors.toString();
}
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return throwError(errMsg);
}
}