2015-02-08 47 views
1

我知道你可以通过构造类似这样的消息:nodejs使用的Error构造函数的参数是什么?

err = new Error('This is an error'); 

,但有更多的参数,它可以处理这样一个错误的名字,错误代码等..?

我也可以将它们设置是这样的:

err.name = 'missingField'; 
err.code = 99; 

,但为了简便起见,我想这些传递给构造函数,如果它可以接受。

我可以包装该功能,但只想在需要的时候这样做。

构造函数或文档的代码在哪里?我搜索了网页,nodejs.org网站和github,但没有找到它。

回答

2

您在node.js中使用的Error类不是特定于节点的类。它来自JavaScript。

由于MDN州,Error构造函数的语法如下:

new Error([message[, fileName[, lineNumber]]]) 

fileNamelineNumber不规范的特点。

为了将自定义属性您可以手动添加到Error类的实例,或者创建自定义的错误,像这样:

// Create a new object, that prototypally inherits from the Error constructor. 
function MyError(message, code) { 
    this.name = 'MyError'; 
    this.message = message || 'Default Message'; 
    this.code = code; 
} 
MyError.prototype = Object.create(Error.prototype); 
MyError.prototype.constructor = MyError; 
相关问题