2017-02-23 103 views
0

我扔使用Error()對象中的錯誤的簡化函數,如下所示:的Javascript從錯誤檢索錯誤名稱和消息()對象

function errorExample() { 
    try { 
    throw new Error('ConnectionError', 'cannot connect to the internet') 
    } 
    catch(error) { 
    console.log(error 
    } 
} 

我希望能夠從內部訪問錯誤名稱和消息catch語句。

根據Mozilla Developer Network我可以通過error.proptotype.nameerror.proptotype.message訪問它們,但是使用上面的代碼我收到undefined。

有沒有辦法做到這一點?謝謝。

+0

參見[自定義錯誤類型](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Ty如果你想要自己的名字,@ MDN)。 –

回答

3

您誤解了文檔。

所有Error實例上都存在Error.prototype的字段。由於error是構造函數Error的一個實例,因此您可以編寫error.message

0

默認情況下,錯誤的名稱是 '錯誤',你可以重寫它:

function errorExample() { 
    try { 
    var e = new Error('cannot connect to the internet'); 
    e.name = 'ConnectionError'; 
    throw e; 
    } 
    catch(error) { 
    console.log(error.name); 
    console.log(error.message); 
    } 
} 

參見:Error.prototype.name

0

試試這個

function errorExample() { 
    try { 
    throw new Error('ConnectionError', 'cannot connect to the internet'); 
    } 
    catch(error) { 
    console.log(error.message); 
    console.log(error.name); 
    } 
} 
errorExample() ;