In my Angular app, I am using a Material dialog to display any error messages that occur to the end user. I built en error service that can has methods to interact with server-side (http) errors and client-side errors.
import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ErrorService {
getClientMessage(error: Error): string {
if (!navigator.onLine) {
return 'No Internet Connection';
}
return error.message ? error.message : error.toString();
}
getClientStack(error: Error): string {
return error.stack;
}
getServerMessage(error: HttpErrorResponse): string {
console.log(error.statusText);
return error.statusText;
}
getServerStack(error: HttpErrorResponse): string {
// handle stack trace
return 'stack';
}
}
I am using an http interceptor to grab the http errors.
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor() {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
return throwError(error);
})
);
}
}
As you can see, I retry the hitting of the endpoint once and then catch any errors. I then am running all errors through a global error handler that extends the Angular ErrorHandler.
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import {
HttpErrorResponse,
HttpHeaders,
HttpClient
} from '@angular/common/http';
import { PathLocationStrategy } from '@angular/common';
import { throwError, Observable } from 'rxjs';
import * as StackTrace from 'stacktrace-js';
import { LoggerService } from '../core/logger.service';
import { ErrorService } from '../core/error.service';
import { MatDialog } from '@angular/material';
import { ErrorDialogComponent } from './error-dialog.component';
@Injectable({
providedIn: 'root'
})
export class GlobalErrorHandler implements ErrorHandler {
// Error handling is important and needs to be loaded first.
// Because of this we should manually inject the services with Injector.
constructor(
private injector: Injector,
public dialog: MatDialog,
private http: HttpClient
) {}
// Function to handle errors
handleError(error: Error | HttpErrorResponse) {
const errorService = this.injector.get(ErrorService);
const logger = this.injector.get(LoggerService);
console.log('error: ', error);
// Header options for http post
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
// Message variable to hold error message
let message;
// Variable to hold stacktrace
let stacktrace;
// Variable to hold url location of error
const url = location instanceof PathLocationStrategy ? location.path() : '';
if (error instanceof HttpErrorResponse) {
// Server error
message = errorService.getServerMessage(error);
stacktrace = errorService.getServerStack(error);
} else {
// Client Error
message = errorService.getClientMessage(error);
stacktrace = errorService.getClientStack(error);
}
// log errors
logger.logError(message, stacktrace);
console.log('message: ', message);
this.openDialog(message);
return throwError(error);
}
openDialog(data): void {
const dialogRef = this.dialog.open(ErrorDialogComponent, {
width: '60%',
data: data
});
dialogRef.afterClosed().subscribe((result) => {
// Redirect back to home (dashboard)?
console.log('in afterClosed: ' + result);
});
}
}
This is where I have logic to check whether the error is server-side or client-side. I then hit the appropriate error service methods.
Issue The real issue I am having is with the dialog box. As you can see, I am opening a dialog box and displaying an error component. This component has the user-friendly view for the end user. Here is my error dialog component..
import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
@Component({
selector: 'app-error-dialog',
templateUrl: './error-dialog.component.html'
})
export class ErrorDialogComponent implements OnInit {
constructor(
@Inject(MAT_DIALOG_DATA) public data: any,
private dialogRef: MatDialogRef<ErrorDialogComponent>
) {}
ngOnInit() {
console.log('data in oninit: ', this.data);
}
/**
* onCancelClick method
* Closes the Material Dialog
*
* @returns :void
*
*/
onCloseClick(): void {
console.log('data in onCloseClick: ', this.data);
this.dialogRef.close('Eureka!');
}
}
note: I added the oninit for testing purposes. It was not in my original code.
I added two buttons to my view to test the error logic...
// html
<button (click)="throwError()">Error</button>
<button (click)="throwHttpError()">HTTP</button>
// component
throwError() {
throw new Error('My Error');
}
throwHttpError() {
this.http.get('someUrl').subscribe();
}
When I click the client-side error, everything happens like designed. When I click the http error button, it opens the dialog, the console.log within the ngoninit does not fire...and when I click the close button, it fires, but the afterClosed does not and the dialog does not close.
So I am wondering what the issue might be...zones? not subscribing properly to the observable?