首页 > 解决方案 > 如何以编程方式访问 NodeJS 异常文本

问题描述

NodeJS 中的异常对象具有不寻常的结构。我希望能够访问错误消息,但它不是对象的命名属性。例如:

var fs = require("fs");

function main() {
   "use strict";

   try {
      var stats = fs.statSync("./nonexistantFile.txt");
      console.log(stats);
   }
   catch (exception) {
      console.error("exception: " + JSON.stringify(exception));
      console.log(exception);
   }
};

main();

此代码打印以下输出:

exception: {"errno":-2,"code":"ENOENT","syscall":"stat","path":"./nonexistantFile.txt"}
{ [Error: ENOENT: no such file or directory, stat './nonexistantFile.txt']
  errno: -2,
  code: 'ENOENT',
  syscall: 'stat',
  path: './nonexistantFile.txt' }

您可以看到它console.log()以某种方式打印错误文本消息,使其看起来是对象的一部分。该文本是异常对象的一部分吗?或者它是console.log()在添加什么东西?

我希望能够捕获错误文本消息并将其存储。如何访问该消息?

标签: javascriptnode.jsexception

解决方案


只需使用exception.message.

可以在此处找到更多信息:MDN Web Docs 中的错误


推荐阅读