Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 885
ciso Avatar asked Feb 08 '15 21:02

ciso


People also ask

What is the error in constructor?

A constructor is used to create a new object and set values for existing object properties. The Error() constructor in JavaScript is used to create new error objects. Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.

What is the use of constructor in node JS?

The constructor method is a special method of a class for creating and initializing an object instance of that class.

Which of the following error codes is are valid in node JS?

An error in Node. js is any instance of the Error object. Common examples include built-in error classes, such as ReferenceError , RangeError , TypeError , URIError , EvalError , and SyntaxError .

What is error handling in node JS?

The exception handling refers to the mechanism by which the exceptions occurring in a code while an application is running is handled. Node. js supports several mechanisms for propagating and handling errors. This are the different methods which can be used for exception handling in Node.


1 Answers

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;
like image 123
Vsevolod Goloviznin Avatar answered Oct 03 '22 21:10

Vsevolod Goloviznin