角度错误处理和记录-调用GlobalErrorHandler的handleError [英] Angular error handling and logging - Call GlobalErrorHandler's handleError

查看:40
本文介绍了角度错误处理和记录-调用GlobalErrorHandler的handleError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里关注Angular错误处理/记录教程:

I'm following an Angular error handling/logging tutorial here: https://www.code-sample.com/2017/09/angular-4-error-handling-and-logging.html

我的问题是-如何从以下位置调用 handleError 方法(位于 global-error-handler.service.ts 文件中,如下面的第3步所示)我的一项服务?

My question is - how can I call the handleError method (residing in the global-error-handler.service.ts file, seen in step 3 below) from one of my services?

在我的 ErrorLogService 中,我还实例化了 POST 请求(数据来自组件),并使用 catchError 尝试从 global-error-handler.service.ts 调用 handleError ,但是我得到 [ts]属性'handleError'在类型上不存在'typeof GlobalErrorHandler'. :

In my ErrorLogService, I'm also instantiating a POST request (with data coming from a component) and using catchError to try and call handleError from global-error-handler.service.ts, but I'm getting [ts] Property 'handleError' does not exist on type 'typeof GlobalErrorHandler'.:

ErrorLogService :

  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 –在app.module.ts中,导入服务,全局处理程序和错误处理程序:

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 { }

推荐答案

我明白了!我最终使用了另一个教程,在该教程中,他们在 App.Module.ts 中以不同的方式实例化了GlobalErrorHandlerService.完成此工作(一个漂亮的错误处理教程): https://www.concretepage.com/angular/angular-custom-error-handler

I got it! I ended up using another tutorial where they instantiate the GlobalErrorHandlerService differently within App.Module.ts. Following this worked (a beautiful error handling tutorial): https://www.concretepage.com/angular/angular-custom-error-handler

在其中,他们在 app.module.ts 中执行了以下操作(请注意 providers 数组):

In it, within app.module.ts they did the following (note the providers array):

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

此外,就我而言,我不应该尝试调用 handleError . GlobalErrorHandlerService 会覆盖默认的 ErrorHandler .因此,在我的'GlobalErrorHandlerService'中创建的新 handleError 方法将自动或通过使用'throw'关键字(在您观察到的是 .subscribe 的对象)上引发错误.d).

Also, in my case I should never have been trying to call handleError. GlobalErrorHandlerService overrides the default ErrorHandler. Thus, the new handleError method created in my 'GlobalErrorHandlerService' will have errors thrown to it automatically or by using the 'throw' keyword (on observables that you're .subscribed to).

如果您在使用Angular Global Error Handling时遇到问题,请仔细阅读以上教程.

Please take a good look at the above tutorial if you're having trouble with Angular Global Error Handling.

这篇关于角度错误处理和记录-调用GlobalErrorHandler的handleError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆