ciso
ciso

Reputation: 3050

What are the arguments for the Error constructor function that nodejs uses?

I know you can pass the Constructor a message like this:

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

but are there more arguments that it could handle like an error name, error code, etc...?

I could also set them like this:

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

but for brevity I'd like to pass these to the constructor if it can accept them.

I could wrap the function, but only want to do that if needed.

Where is the code for the constructor or the documentation? I've searched the web, the nodejs.org site and github and haven't found it.

Upvotes: 6

Views: 3556

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

The Error class that you use in node.js is not a node-specific class. It comes from JavaScript.

As MDN states, the syntax of the Error constructor is the following:

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

Where fileName and lineNumber are not standard features.

To incorporate custom properties you can either add the manually to an instance of Error class, or create your custom error, like this:

// 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;

Upvotes: 4

Related Questions