2016-06-14 2 views
0

Я создал ошибку пользовательской машинописи, которая основывается на несколько источников, кажется, идет так:пойманной Машинопись пользовательских ошибки не могут быть проверены на его тип

export class Exception extends Error { 

    constructor(public message: string) { 
     super(message); 
     this.name = 'Exception'; 
     this.message = message; 
     this.stack = (<any>new Error()).stack; 
    } 
    toString() { 
     return this.name + ': ' + this.message; 
    } 
} 

export class SpecificException extends Exception { 

} 

В моем коде я тогда бросить это с помощью простого:

throw new SpecificException('foo'); 

И в другом месте я ловлю его:

catch (e) { 
    var t1 = Object.getPrototypeOf(e); 
    var t2 = SpecificException.prototype; 

    if (e instanceof SpecificException) { 
    console.log("as expected"); 
    } 
    else { 
    console.log("not as expected"); 
    } 
} 

Этот код печатает "как ожидалось". Любые идеи почему?

Позже редактировать

Как @basarat указывает, приведенную ниже, погрешность ожидаемого типа. После дальнейших исследований я понял, что это связано с дублированием модуля, связанным с моей средой, возможно, из-за использования мокко в режиме просмотра.

+2

Вы уверены? Для меня истинны как «e instanceof Exception», так и «e instanceof SpecificException». –

ответ

4

Побежал следующий код:

declare global { 
    interface Error { 
     stack: any; 
    } 
} 
class Exception extends Error { 

    constructor(public message: string) { 
     super(message); 
     this.name = 'Exception'; 
     this.message = message; 
     this.stack = (<any>new Error()).stack; 
    } 
    toString() { 
     return this.name + ': ' + this.message; 
    } 
} 
class SpecificException extends Exception { 

} 

try { 
    throw new SpecificException('foo'); 
} 
catch (e) { 
    var t1 = Object.getPrototypeOf(e); 
    var t2 = SpecificException.prototype; 

    if (e instanceof SpecificException) { 
    console.log("as expected"); 
    } 
    else { 
    console.log("not as expected"); 
    } 
} 

Got желаемого результата:

as expected 

Так нет ошибки размещена в задаваемом вопросе