代码之家  ›  专栏  ›  技术社区  ›  Kyle Vassella

角度错误处理和记录-调用GlobalErrorHandler的handleError

  •  0
  • Kyle Vassella  · 技术社区  · 6 年前

    下面是一个角度错误处理/记录教程: https://www.code-sample.com/2017/09/angular-4-error-handling-and-logging.html

    我的问题是-我怎么称呼 handleError 方法(位于 global-error-handler.service.ts 文件,见下面的步骤3)从我的服务之一?

    在我的 ErrorLogService ,我也在实例化 POST 请求(包含来自组件的数据)并使用 catchError 试着打电话 手错误 全局错误处理程序.service.ts 但是我正在 [ts] Property 'handleError' does not exist on type 'typeof GlobalErrorHandler'. :

    错误登录服务 :

      postData(body):Observable<any>{
    
        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json'
          }),
          withCredentials: true
        }
        return this.http.post(this.baseUrl2, body, httpOptions)
        .pipe(
          catchError(GlobalErrorHandler.handleError)
        )
      }
    


    步骤1-为全局错误消息创建AppConstants类(AppConstants.ts):

    export class AppConstants {
    public static get baseURL(): string { return 'http://localhost:4200/api'; }
    public static get httpError(): string { return 'There was an HTTP error.'; }
    public static get typeError(): string { return 'There was a Type error.'; }
    public static get generalError(): string { return 'There was a general error.'; }
    public static get somethingHappened(): string { return 'Nobody threw an Error but something happened!'; }
    }
    

    步骤2“创建错误日志服务(ErrorLogService)进行错误日志记录:

    import { Injectable} from '@angular/core';
    import { HttpErrorResponse } from '@angular/common/http';
    import{ AppConstants} from '../app/constants'
    // my import of globalErrorHandler, so I can (hopefully) use its handleError method
    import { GlobalErrorHandler } from '../global-error-handler/global-error-handler';
    
    //#region Handle Errors Service
    @Injectable()
    export class ErrorLogService {
    
      constructor() {  }
    
      //Log error method
      logError(error: any) {
        //Returns a date converted to a string using Universal Coordinated Time (UTC).
        const date = new Date().toUTCString();
    
        if (error instanceof HttpErrorResponse) {
          //The response body may contain clues as to what went wrong,
          console.error(date, AppConstants.httpError, error.message, 'Status code:',
                                                      (<HttpErrorResponse>error).status);
        }
        else if (error instanceof TypeError) {
          console.error(date, AppConstants.typeError, error.message, error.stack);
        }
        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);
        }
        else {
          console.error(date, AppConstants.somethingHappened, error.message, error.stack);
        }
      }
    }
    //#endregion
    

    步骤3-创建全局错误处理程序服务(globalErrorHandler.service.ts),以便使用错误日志服务记录错误。

    import { Injectable, ErrorHandler } from '@angular/core';
    import {ErrorLogService} from './error-log.service';
    
    // Global error handler for logging errors
    @Injectable()
    export class GlobalErrorHandler extends ErrorHandler {
        constructor(private errorLogService: ErrorLogService) {
           //Angular provides a hook for centralized exception handling.
           //constructor ErrorHandler(): ErrorHandler
            super();
        }
    
        handleError(error) : void {
            this.errorLogService.logError(error);
        }
    }
    

    步骤4“in app.module.ts,import services,global handler and error handler:

    import { NgModule, ErrorHandler } from '@angular/core';
    import {ErrorLogService} from './error-logg.service';
    import {GlobalErrorHandler} from './global-error.service';
    
    @NgModule({
      declarations: [
        AppComponent,
        LoginComponent,
        UserComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule,
        RouterModule.forRoot([
          { path: '', component: AppComponent, pathMatch: 'full', canActivate: [AuthGuard]},
          { path: 'user', component: UserComponent, canActivate: [AuthGuard]},
          { path: 'login', component: LoginComponent}])
      ],
      providers: [ ErrorLogService, // register global error log service
                  GlobalErrorHandler,// register global error handler
                  EmployeeService, // register Employee service
                  ValidationService, //register Validation Service
                  AuthenticationService, //register Authentication Service
                  UserService],//register User Service
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Kyle Vassella    6 年前

    我得到了它! 最后我使用了另一个教程,在其中他们以不同的方式实例化了GlobalErrorHandlerService App.Module.ts . 遵循这一点(一个漂亮的错误处理教程): https://www.concretepage.com/angular/angular-custom-error-handler

    在里面,在里面 app.module.ts 他们做了以下工作(注意 providers 数组):

    @NgModule({
      ------
      providers: [
        GlobalErrorHandlerService,
        { provide: ErrorHandler, useClass: GlobalErrorHandlerService },
        -----    
      ]
    })
    export class AppModule { } 
    

    而且,在我的情况下,我不应该打电话给 handleError . GlobalErrorHandlerService 覆盖默认值 ErrorHandler . 因此,新的 手错误 在我的“globalErrorHandlerService”中创建的方法将自动或通过使用“throw”关键字(在 .subscribe D)。

    如果您在角度全局错误处理方面遇到问题,请仔细阅读以上教程。