javascript异常对象格式 [英] javascript exception object format
问题描述
默认情况下,当找不到文件时,Node.js会引发以下异常。
By default, Node.js throws the following exception when a file is not found.
{ [Error: ENOENT, no such file or directory 'InvalidFile']
errno: 34,
code: 'ENOENT',
path: 'InvalidFile',
syscall: 'open' }
从技术上讲,这应该是一个JavaScript对象。根据javascript对象的语义,应该有一个逗号来分隔成员元素。在这种情况下,之间没有逗号[错误:ENOENT,没有这样的文件或目录InvalidFile]
和 errno:34,
。我的问题是
Technically speaking, this is supposed to be a JavaScript Object. As per the javascript object sematics, there should be a comma to separate member elements. In this case, there is no comma between [Error: ENOENT, no such file or directory 'InvalidFile']
and errno: 34,
. My questions are
-
如何构建这样的对象?
How do I construct an object like this?
如何在程序中访问
[错误:ENOENT,没有这样的文件或目录'InvalidFile']
元素
?
How do I access the
[Error: ENOENT, no such file or directory 'InvalidFile']
element
in a program?
推荐答案
嗯,这不完全是代码。它基于JavaScript的文字语法,但仅仅是从 <$ c $生成的对象的表示c> util.inspect() (或类似的内部函数)。
Well, it's not entirely code. It's based on JavaScript's literals syntax, but is just a representation of a the object that's generated from util.inspect()
(or a similar internal function).
方括号提到类型 错误
之前的 消息
。而且,其余的是可列举的属性及其添加的值。
The square brackets mention the type of Error
before its message
. And, the rest is a list of enumerable properties and their values that were added to it.
自己创建它:
var error = new Error("ENOENT, no such file or directory 'InvalidFile'");
error.errno = 34;
error.code = 'ENOENT';
error.path = 'InvalidFile';
error.syscall = 'open'
console.log(error); // uses `util.inspect()`
console.log(util.inspect(error)); // or use it directly
console.log(error.message); // "ENOENT, no such ..."
console.log(Object.prototype.toString.call(error)); // "[object Error]"
而且,对于更大的格式示例,请尝试记录一些内置模块:
And, for a larger sample of the format, try logging some built in modules:
console.log(console);
{ log: [Function],
info: [Function],
warn: [Function],
error: [Function],
dir: [Function],
time: [Function],
timeEnd: [Function],
trace: [Function],
assert: [Function],
Console: [Function: Console] }
这篇关于javascript异常对象格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!