js 打印錯誤堆棧


Error對象

一旦代碼解析或運行時發生錯誤,JavaScript引擎就會自動產生並拋出一個Error對象的實例,然后整個程序就中斷在發生錯誤的地方。

Error對象的實例有三個最基本的屬性:

  • name:錯誤名稱
  • message:錯誤提示信息
  • stack:錯誤的堆棧(非標准屬性,但是大多數平台支持)

利用name和message這兩個屬性,可以對發生什么錯誤有一個大概的了解。

  1.  
    if (error.name){
  2.  
    console.log(error.name + ": " + error.message);
  3.  
    }
  4.  
     

上面代碼表示,顯示錯誤的名稱以及出錯提示信息。

stack屬性用來查看錯誤發生時的堆棧。

function throwit() {
  throw new Error('');
}
 
function catchit() {
  try {
    throwit();
  } catch(e) {
    console.log(e.stack); // print stack trace
  }
}
 
catchit()
// Error
//    at throwit (~/examples/throwcatch.js:9:11)
//    at catchit (~/examples/throwcatch.js:3:9)
//    at repl:1:5

 

上面代碼顯示,拋出錯誤首先是在throwit函數,然后是在catchit函數,最后是在函數的運行環境中。

 

Error.prototype 對象包含如下屬性:

  • constructor--指向實例的構造函數
  • message--錯誤信息
  • name--錯誤的名字(類型)
    上述是 Error.prototype 的標准屬性, 此外, 不同的運行環境都有其特定的屬性. 在例如 Node, Firefox, Chrome, Edge, IE 10+, Opera 以及 Safari 6+ 這樣的環境中, Error 對象具備 stack 屬性, 該屬性包含了錯誤的堆棧軌跡. 一個錯誤實例的堆棧軌跡包含了自構造函數之后的所有堆棧結構.

  1. Errors 也可以被作為其它對象, 你也不必拋出它們, 這也是為什么大多數回調函數把 Errors 作為第一個參數的原因。
const fs = require('fs'); fs.readdir('/example/i-do-not-exist', function callback(err, dirs) { if (err instanceof Error) { // `readdir` will throw an error because that directory does not exist // We will now be able to use the error object passed by it in our callback function console.log('Error Message: ' + err.message); console.log('See? We can use Errors without using try statements.'); } else { console.log(dirs); } });
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM