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.
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.
The constructor method is a special method of a class for creating and initializing an object instance of that class.
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 .
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With