CodeBlanks Logo Icon CodeBlanks

The Error class

Learn the Error class and its properties.

The Error class

In Node.js Error is a built-in class. When something goes wrong you throw it with throw new Error("message"). Every Error object has three important properties: message, stack and name.

message is the human-readable description of the error. stack is the call trace showing where the error was thrown; it includes file names and line numbers. name is the name of the error class; for Error it is "Error". For example, const err = new Error("failed"); console.log(err.name) prints Error. This lets you tell the type and source of an error apart.

Creating an Error

An Error object is created with new Error("message"). The new keyword creates a new instance. You can throw the error you created with throw or keep it in a variable.

For example, const err = new Error("file missing"); creates an error object but does not throw it. Writing throw err; propagates the error upward from that point, and if nothing catches it the program crashes. err.message is "file missing" and err.name is "Error". err.stack gives the call trace. This makes the error both informative and traceable; it is easy to find in debuggers.

Practice Create an Error and print its name

Create an error with new Error("failed") and put it in err. Print err.name with console.log.

Starter code

index.js
// Create a new Error
// Print its name property
// write here

Sample solution

index.js
const err = new Error("failed");
console.log(err.name);

Expected output

Error

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which property of an Error holds the call trace?

index.js
err.stack
  • message
  • name
  • code
  • stack Correct answer

Explanation: The stack property holds the call trace.

2 Throw an Error

Question
throw new ____("mesaj");
Answer
throw new Error("mesaj");

Explanation: throw new Error throws an error.

3 Match each property to its meaning

Term Meaning
message Error message
stack Call trace
name Error type
new Error Creates a new error

All lessons in Intermediate