2017-08-15 36 views
2

我希望能夠擁有一個類ChildError,該類的默認屬性有一些基本定義:codemessage如何獲得基本屬性並重新定義它們?

但是,當我真的會拋出這個錯誤時,我可能會重新定義message的值。如果是這種情況,我想使用新的定義,而不是由ChildError定義的定義。

下面是一個例子:

class BaseError extends Error { 

    public code: number = 0; 

    constructor(arg: any = {}) { 
     super(typeof arg === 'string' ? arg : arg.message); 

     this.message = arg.message; 
     this.code = arg.code; 
    } 

    getMessage =(): string => { 
     return this.message; 
    } 
} 

class ChildError extends BaseError { 
    code = 2; 
    message = 'This is the child error message'; 
} 

const cError = new ChildError({ message: 'hello' }); 
console.log('print : ', cError.getMessage()); 

它打印This is the child error message 不過,我想hello要打印

這裏是一個Playground link

在transpiled JavaScript中,它看起來像這樣沒有按不起作用,因爲在我們分配默認值codemessage之前通過的參數被處理,因此它們會被覆蓋ñ。如何避免這種情況?我想要在默認值後處理參數!

而且,在構造一個console.log將打印this.messagehello像我們想,這是當我們嘗試它返回This is the child error messagegetMessage()訪問它。

我已閱讀本SO thread,但它似乎並不適用,因爲該屬性是不一樣的類名對我來說...

回答

0

你需要或者檢查消息屬性存在不嘗試這種方式

class ChildError extends BaseError { 
    constructor(arg: any) { 
     if (!arg.hasOwnProperty('message')) 
      arg.message = "This is the child error message"; 
     super(arg);    
    } 
} 

如果你打算不允許的,而不是

if (!arg.hasOwnProperty('message')) 

使用falsy值只是

if (!arg.message) 
0

ChildError接收與對象就聲明構造消息,並默認爲message,像這樣:

class BaseError extends Error { 

    constructor(arg: any = {}) { 
     super(typeof arg === 'string' ? arg : arg.message); 

     this.message = arg.message; 
    } 

    getMessage =(): string => { 
     return this.message; 
    } 
} 

class ChildError extends BaseError { 
    code = 2; 

    constructor(arg) { 
     super(arg || { message: 'This is the child error message' }) 
    } 
} 

const cError = new ChildError({ message: 'hello' }); 
console.log('print : ', cError.getMessage()); 
+1

你應該考慮如果我實例ChildError傳遞作爲參數的對象沒有消息屬性。它不會按預期工作。嘗試調用新的ChildError({foo:「Hello」});你回到控制檯打印:未定義 –

相關問題