简体   繁体   English

角度4,自定义ErrorHandler无法识别自定义错误

[英]Angular 4, custom ErrorHandler doesn't recognize custom Error

I tried to create a custom global ErrorHandler and 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. 在我的app.component中,我抛出一个ApplicationError(在ngOnInit中),我的ErrorHandler被成功调用。 But my error in handleError is always of type Error and error.originalError is always undefined no matter if I throw my custom error and there the if will never resolve to true. 但是我在handleError中的Error始终是Error类型,并且error.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? 任何想法可能导致此问题的原因以及如何解决?

EDIT As suspected it has something to do with Debugmode. 编辑由于怀疑它与Debugmode有关。 As soon as I enable prodmode with enableProdMode(); 一旦我使用enableProdMode enableProdMode();启用prodmode enableProdMode(); it works as expected. 它按预期工作。

Still this doesn't really answer my question yet. 但这还不能真正回答我的问题。

How can I handle my custom error in angular's debug mode? 如何在angular的调试模式下处理自定义错误?

You encounter this problem because ApplicationError is 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? 为什么这需要是Error的一个实例? Because your error pass through the following method: 因为您的错误通过以下方法传递:

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 Error instance, 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生命周期调用的方法(例如:handler,lifecycle-hook)返回承诺被拒绝的承诺时。

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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular-用于自定义HTTP错误处理的拦截器的ErrorHandler - Angular - ErrorHandler for interceptor for custom HTTP error handling 角材料SnackBar和自定义ErrorHandler通知错误 - Angular Material SnackBar and custom ErrorHandler to notify error 在Angular自定义ErrorHandler中使用服务 - Using Service in Angular Custom ErrorHandler Angular:为什么在我的自定义 ErrorHandler 中订阅主题不触发? - Angular: Why don't subscriptions to a Subject in my custom ErrorHandler fire? Angular2在自定义ErrorHandler中注入服务 - Angular2 Injecting services in custom ErrorHandler 角度4:主题或BehaviorSubject的自定义errorHandler不起作用 - Angular 4: Custom errorHandler with Subject Or BehaviorSubject not working Angular 如何在自定义ErrorHandler中使用HttpClient? - Angular how to use HttpClient in custom ErrorHandler? 为什么在Angular 2中,ErrorHandler模​​块不存在? - Why in Angular 2, ErrorHandler module doesn't exist? 使用自定义错误处理程序捕获Javascript错误后,Angular / Angular2数据绑定无法正常工作 - Angular/Angular2 data binding not working after catching Javascript error using custom errorhandler 如何在自定义 ErrorHandler 中解决 Angular 8 应用程序中的“无法解析 […] 的所有参数”问题? - How to solve “Can't resolve all parameters for […]” issue in Angular 8 application in a custom ErrorHandler?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM