cic-staff-client/src/app/_helpers/global-error-handler.ts

62 lines
1.9 KiB
TypeScript
Raw Normal View History

import {ErrorHandler, Injectable} from '@angular/core';
import {LoggingService} from '@app/_services';
import {HttpErrorResponse} from '@angular/common/http';
@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
private sentencesForWarningLogging: string[] = [];
private loggingService: LoggingService;
constructor() {
super();
}
handleError(error: any): void {
this.logError(error);
const message = error.message ? error.message : error.toString();
if (error.status) {
error = new Error(message);
}
const errorTraceString = `Error message:\n${message}.\nStack trace: ${error.stack}`;
const isWarning = this.isWarning(errorTraceString);
if (isWarning) {
this.loggingService.sendWarnLevelMessage(errorTraceString, {error});
} else {
this.loggingService.sendErrorLevelMessage(errorTraceString, this, {error});
}
throw error;
}
logError(error: any): void {
if (error instanceof HttpErrorResponse) {
this.loggingService.sendErrorLevelMessage(
`There was an HTTP error. ${error.message}, Status code: ${(error as HttpErrorResponse).status}`, this, {error});
} else if (error instanceof TypeError) {
this.loggingService.sendErrorLevelMessage(`There was a Type error. ${error.message}`, this, {error});
} else if (error instanceof Error) {
this.loggingService.sendErrorLevelMessage(`There was a general error. ${error.message}`, this, {error});
} else {
this.loggingService.sendErrorLevelMessage('Nobody threw an error but something happened!', this, {error});
}
}
private isWarning(errorTraceString: string): boolean {
let isWarning = true;
if (errorTraceString.includes('/src/app/')) {
isWarning = false;
}
this.sentencesForWarningLogging.forEach((whiteListSentence) => {
if (errorTraceString.includes(whiteListSentence)) {
isWarning = true;
}
});
return isWarning;
}
}