Node.js Creating Error object


Example

new Error(message)

Creates new error object, where the value message is being set to message property of the created object. Usually the message arguments are being passed to Error constructor as a string. However if the message argument is object not a string then Error constructor calls .toString() method of the passed object and sets that value to message property of the created error object.

var err = new Error("The error message");
console.log(err.message); //prints: The error message
console.log(err);
//output
//Error: The error message
//    at ... 

Each error object has stack trace. Stack trace contains the information of error message and shows where the error happened (the above output shows the error stack). Once error object is created the system captures the stack trace of the error on current line. To get the stack trace use stack property of any created error object. Below two lines are identical:

console.log(err);
console.log(err.stack);