我有一个Angular应用程序,用于容纳多个子应用程序。在这个应用程序中,我实现了一个GlobalErrorHandlerService
,它覆盖了Angular的默认ErrorHandler
:
global-error-handler.service.ts
import { Injectable, ErrorHandler, Injector } from '@angular/core';
import {ErrorLogger} from '../services/error-logger.service';
import { HttpErrorResponse } from '@angular/common/http';
// Global error handler for logging errors
@Injectable()
export class GlobalErrorHandlerService extends ErrorHandler {
constructor(private injector : Injector, private errorLoggerService: ErrorLoggerService) {
super();
}
handleError(error: any) {
let loggerService = this.injector.get(ErrorLoggerService);
loggerService.logError(error)
.subscribe(
data => console.warn(data),
error => {throw error},
() => console.log("empty")
);
}
}
这会自动捕获所有错误并将其发送到全局ErrorLoggerService
,以将这些错误记录到数据库中:
error-logger.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpRequest, HttpHeaders, HttpInterceptor, HttpHandler, HttpEvent, HttpParams, HttpErrorResponse} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { from } from 'rxjs';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';
import { AppConstants } from '../app-constants/app-constants';
@Injectable({
providedIn: 'root'
})
export class ErrorLoggerService {
constructor(private http: HttpClient) { };
logError(error: any):Observable<any> {
const date = new Date().toUTCString();
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
withCredentials: true
};
//******** log errors based on type ********//
if (error instanceof HttpErrorResponse) {
//** POST error to db **//
return this.http.post('http://path-to-my-api-model-which-logs-to-db',
{ Date: date, type: error.type, message: error.message, stackTrace: "testStackTraceSERVICE", lineNumber: "testLineNumber", code: "testCode" },
httpOptions)
}
else if (error instanceof TypeError) {
//** POST error to db **//
return this.http.post('http://path-to-my-api-model-which-logs-to-db',
{ Date: date, type: error.name, message: error.message, stackTrace: error.stack, lineNumber: "TypeError lineNumber", code: "testCode" },
httpOptions)
}
else if (error instanceof Error) {
console.error(date, AppConstants.generalError, error.message, error.stack);
}
else if(error instanceof ErrorEvent){
//A client-side or network error occurred. Handle it accordingly.
console.error(date, AppConstants.generalError, error.message, error.filename);
}
else {
console.error(date, AppConstants.somethingHappened, error.message, error.stack);
}
}
}
这将正确记录到数据库。但是,在此数据库表中记录了我们的错误,我想创建一个Application
列,并希望用发生错误的子应用程序的名称填充。
我该如何完成?有没有办法拉出发生错误的模块,或者类似的方法?这样,我可以将ErrorLoggerService
条件包装在较大的if语句中,该语句的内容如下:
if (error is from Application A) {
var appName = Application A;
//log errors to db
} else if (error is from Application B) {
var appName = Application A:
//log errors to db
}