Sunday, 20 October 2019

Preventing multiple errors displaying via toastie

I am have implemeted httpinterceptor in my angular 8 application and redirecting the to systemmaintenance page when the service is offline. I also displaying a toatie message via the alert service.At the moment what is happenning is that the system emits number of error messages apart from No network message. So basically the catch block is executing the return throwError(error); multiple times hence you can see multiple messages. How do I stop after the first toastie message is shown

One reason that these messages appear is also because one the user tries to navigate to that page, the methods fire to fetch the data from the back end and since the service is offline, the error messages from the respective methods are thrown. Do I need to prevent the user from accessing the component itself and handle it in the router or do I need to manage the toastie messages ones they are thrown. I feel it makes sense for me to handle in the router but not not sure how to do it

Screenshot

enter image description here

This is what this.alertService.resetStickyMessage() is in the httpwebinterceptor

 private stickyMessages = new Subject<AlertMessage>();

 export class AlertMessage {
    constructor(public severity: MessageSeverity, public summary: string, public detail: string, public timeOutSeconds?: number) { }
  }

  resetStickyMessage() {
        this.stickyMessages.next();
    }

Httpinterceptor class

@Injectable()
export class HttpWebInterceptor implements HttpInterceptor {

    constructor(public router: Router,
        private authService: AuthService,
        private alertService: AlertService
    ) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        if (!request.headers.has('Content-Type')) {
            request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
        }

        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    console.log('event', event);
                    if(event.status == HttpStatusCode.OK)
                    {
                         if (this.router.url == '/offline') {
                             // Website is back online
                             console.log('redirecting to login');
                             this.authService.gotoLoginPage();
                        }
                    }
                }
                return event;
            }),
            catchError((error: HttpErrorResponse) => {
                if (error.error instanceof Error) {
                    // A client-side or network error occurred. Handle it accordingly.
                    if(isDevMode()) console.error('An error occurred:', error.error.message);
                } 
                else 
                {
                    if(isDevMode()) 
                        console.error('Backend returned code ${error.status}, body was: ${error.error}');

                    switch(error.status)
                    {
                        case HttpStatusCode.Unknown:
                        {
                            if (this.router.url != '/offline')
                            {
                                this.authService.clearUserData();
                                this.alertService.resetStickyMessage();
                                this.alertService.showMessage("No Network", "The server cannot be reached", MessageSeverity.error);
                                this.router.navigate(['offline']);
                                break;
                            }
                        }
                        default:
                            break;
                    }
                }

                return throwError(error);
            }));

    }
}

showMessage

showMessage(summary: string)
    showMessage(summary: string, detail: string, severity: MessageSeverity, timeOutSeconds?: number)
    showMessage(summaryAndDetails: string[], summaryAndDetailsSeparator: string, severity: MessageSeverity)
    showMessage(response: HttpResponseBase, ignoreValue_useNull: string, severity: MessageSeverity)
    showMessage(data: any, separatorOrDetail?: string, severity?: MessageSeverity, timeOutSeconds?: number) {

        if (!severity)
            severity = MessageSeverity.default;

        if (data instanceof HttpResponseBase) {
            data = Utilities.getHttpResponseMessage(data);
            separatorOrDetail = Utilities.captionAndMessageSeparator;
        }

        if (data instanceof Array) {
            for (let message of data) {
                let msgObject = Utilities.splitInTwo(message, separatorOrDetail);
                this.showMessageHelper(msgObject.firstPart, msgObject.secondPart, severity, false);
            }
        }
        else {
            this.showMessageHelper(data, separatorOrDetail, severity, false, timeOutSeconds);
        }
    }


from Preventing multiple errors displaying via toastie

No comments:

Post a Comment