typescript Angular 4,自定义 ErrorHandler 无法识别自定义错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44108285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:34:11  来源:igfitidea点击:

Angular 4, custom ErrorHandler doesn't recognize custom Error

angulartypescripterror-handling

提问by Arikael

I tried to create a custom global ErrorHandlerand followed the instruction detailed here

我尝试创建一个自定义的全局ErrorHandler并按照此处详述的说明进行操作

application-error-handler(just the important parts)

应用程序错误处理程序(只是重要的部分)

@Injectable()
export class ApplicationErrorHandler extends ErrorHandler {

    constructor(private injector: Injector) {
        super(false);
    }

    handleError(error: any): void {

        if (error instanceof ApplicationError || error.originalError instanceof ApplicationError) {
            this.addError(error.originalError);
        }
        else {
            super.handleError(error);
        }
    }

app-module

应用模块

 providers: [
    {
        provide: ErrorHandler,
        useClass: ApplicationErrorHandler
    }
],

app.component(only the important part)

app.component(仅重要部分)

public ngOnInit(): void { 
    const error = new ApplicationError();
    error.message = "fehler";
    throw error;
} 

application-error

应用程序错误

export class ApplicationError implements Error {
    name: string;
    message: string;
    httpStatus?: number = 404;
    applicationStatus?: number;
    errorMessageTranslationkey: string;
    handled: boolean = false;
}

in my app.component I throw an ApplicationError (in ngOnInit), my ErrorHandler gets called successfully. But my error in handleErroris always of type Errorand error.originalErroris always undefinedno matter if I throw my custom error and there the ifwill never resolve to true.

在我的 app.component 中,我抛出了一个 ApplicationError(在 ngOnInit 中),我的 ErrorHandler 被成功调用。但是我的错误handleError始终是类型的Errorerror.originalError并且始终与undefined我是否抛出自定义错误无关,并且if永远不会解析为 true。

I have no idea why and how this happens. What I see is that the error gets, so I assume, wrapped because when I debug I see error: Error: [object: Object] at viewWrappedDebugError (vendor.bundle.js)

我不知道为什么以及如何发生这种情况。我看到的是错误得到了,所以我假设,因为当我调试时我看到error: Error: [object: Object] at viewWrappedDebugError (vendor.bundle.js)

Any idea what might cause this issue and how I can resolve it?

知道可能导致此问题的原因以及如何解决吗?

EDITAs suspected it has something to do with Debugmode. As soon as I enable prodmode with enableProdMode();it works as expected.

编辑怀疑它与调试模式有关。只要我启用 prodmode,enableProdMode();它就会按预期工作。

Still this doesn't really answer my question yet.

这仍然没有真正回答我的问题。

How can I handle my custom error in angular's debug mode?

如何在 angular 的调试模式下处理我的自定义错误?

回答by andreim

You encounter this problem because ApplicationErroris not an Error.

您遇到此问题是因为ApplicationError不是Error.

You can use the following code in order to create a custom error:

您可以使用以下代码来创建自定义错误:

export class ApplicationError extends Error {

  httpStatus?: number = 404;
  applicationStatus?: number;
  errorMessageTranslationkey: string;
  handled: boolean = false;

  constructor(message?: string) {
    super(message);
    this.name = ApplicationError.name;
    Object.setPrototypeOf(this, ApplicationError.prototype);
  }
}

Related to the topic of creating a custom error, check also these links in order to have a full idea on the subject:

与创建自定义错误的主题相关,还请检查这些链接,以便对该主题有一个完整的了解:

Why this needs to be an instance of Error?Because your error pass through the following method:

为什么这需要是 Error 的实例?因为您的错误通过以下方法传递:

function viewWrappedDebugError(err, context) {
    if (!(err instanceof Error)) {
        // errors that are not Error instances don't have a stack,
        // so it is ok to wrap them into a new Error object...
        err = new Error(err.toString());
    }
    _addDebugContext(err, context);
    return err;
}

Code available at errors.ts.

代码可在errors.ts.

Therefore if you are not throwing an Errorinstance, then a new instance is created.

因此,如果您不抛出Error实例,则会创建一个新实例。

Intercepting uncatched promises in ErrorHandler

在 ErrorHandler 中拦截未捕获的承诺

Another error case is when you return a promise which becomes rejected, from your method that is called by the Angular lifecycle (eg: handler, lifecycle-hook).

另一个错误情况是当您从 Angular 生命周期调用的方法(例如:处理程序、生命周期钩子)返回一个被拒绝的承诺时。

export class AppComponent implements OnInit {

  ngOnInit() {
    return new Promise((resolve, reject) => reject(new ApplicationError()));
  }
}

Therefore the error handling code can look like:

因此错误处理代码可能如下所示:

import {ErrorHandler, Injectable, Injector} from "@angular/core";
import {ApplicationError} from "./ApplicationError";

@Injectable()
export class ApplicationErrorHandler extends ErrorHandler {

  private errors: ApplicationError[] = [];

  constructor(private injector: Injector) {
    super(false);
  }

  handleError(error: any): void {

    if (error instanceof ApplicationError) {
      this.addError(error);
    }
    else {
      if(error.rejection instanceof ApplicationError) {
        this.addError(error.rejection);
      }
      else {
        super.handleError(error);
      }
    }
  }

  addError(error: ApplicationError) {
    this.errors.push(error);
  }
}