【问题标题】:Errors thrown in angular 6 resolver lose error custom typeAngular 6 解析器中抛出的错误丢失错误自定义类型
【发布时间】:2019-01-01 16:57:28
【问题描述】:

我试图在我的解析器中抛出自定义错误,这些错误是我用全局错误处理程序捕获的。我可以在组件中抛出错误并且它们可以正常通过,但是当我将它们放入解析器时,它们的类型会更改为标准的 Error 类型。

这是一个正常运行的重现: https://stackblitz.com/edit/angular-gitter-vvgys6

设置

class DisplayableError extends Error {
// ...
}


@Injectable()
export class GlobalErrorHandlerService {
  constructor() { }

  handleError(error) {

    console.log('GOT ERROR instance of DisplayableError', error instanceof DisplayableError);

  }
}

工作用途

在任何组件中我都可以抛出一个错误,它会被全局错误处理程序捕获,它是DisplayableError 的一个实例。

throw new DisplayableError('blah');

使用不当

当我在解析器中抛出错误时,实例类型更改为 Error 并且 instanceof DisplayableError 返回 false。

@Injectable()
export class StoreGetResolver implements Resolve<StoreModel> {
  constructor(
    private storeService: StoreService,
  ) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<StoreModel> {

    let storeId = route.paramMap.get('storeId');
    return this.storeService.get(storeId)
      .catch(error => Observable.throw(new DisplayableError('my custom error')));
  }

}

我也试过了

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<StoreModel> {

  let storeId = route.paramMap.get('storeId');
  return this.storeService.get(storeId)
    .do(
      () => { },
      error => throw new DisplayableError('my custom error')
    );
}

...甚至这个

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<StoreModel> {
  throw new DisplayableError('my custom error');

}

使用正确的数据调用 DisplayableError 的构造函数,消息甚至发送到全局错误处理程序,但错误的类型是 Error 而不是 DisplayableError 到达那里时

【问题讨论】:

    标签: angular error-handling rxjs angular6


    【解决方案1】:

    这是 Typescript 的一个已知问题:https://github.com/Microsoft/TypeScript/issues/13965

    解决方法是对原型进行一些摆弄:

    // Use this class to correct the prototype chain.
    export class MyError extends Error {
        __proto__: Error;
        constructor(message?: string) {
            const trueProto = new.target.prototype;
            super(message);
    
            // Alternatively use Object.setPrototypeOf if you have an ES6 environment.
            this.__proto__ = trueProto;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多