我希望能夠擁有一個類ChildError
,該類的默認屬性有一些基本定義:code
和message
。如何獲得基本屬性並重新定義它們?
但是,當我真的會拋出這個錯誤時,我可能會重新定義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中,它看起來像這樣沒有按不起作用,因爲在我們分配默認值code
和message
之前通過的參數被處理,因此它們會被覆蓋ñ。如何避免這種情況?我想要在默認值後處理參數!
而且,在構造一個console.log
將打印this.message
爲hello
像我們想,這是當我們嘗試它返回This is the child error message
與getMessage()
訪問它。
我已閱讀本SO thread,但它似乎並不適用,因爲該屬性是不一樣的類名對我來說...
你應該考慮如果我實例ChildError傳遞作爲參數的對象沒有消息屬性。它不會按預期工作。嘗試調用新的ChildError({foo:「Hello」});你回到控制檯打印:未定義 –