javascript - 如何以编程方式访问 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()
在添加什么东西?
我希望能够捕获错误文本消息并将其存储。如何访问该消息?
解决方案
只需使用exception.message
.
可以在此处找到更多信息:MDN Web Docs 中的错误
推荐阅读
- python - 按钮不显示计时器
- regex - 正则表达式屏蔽除特定范围以外的所有电话号码
- data-structures - Redis Zset 定位记录
- r - R删除数据框中的重复项
- c++ - “类”在“<”标记错误之前没有命名类型和预期的初始化程序
- javascript - 我可以使用正则表达式来计算一年的世纪吗?
- javascript - 点符号如何在 React.js 的功能组件中工作?
- python - Django 是否使用一个线程来处理 WSGI 或 Gunicorn 中的多个请求?
- javascript - 防止 HTML5 输入上的智能引号
- node.js - 类型错误:.push() 不是函数