JavaScript
The Error object
Learn the Error object's message and name properties and how to create one.
The Error object
In JavaScript Error is an object created with new Error("message"). The created object's message property holds the text you give; the name property holds the error type (by default "Error").
Example: const err = new Error("Invalid input"). Here err.message is "Invalid input" and err.name is "Error". When thrown, the catch block receives this object; so you can learn the error's reason and type.
The message and name properties
The two most used properties of an Error object are message and name. message holds the text you gave when creating it; name gives the error class name.
For example when you create new TypeError("X"), the name property becomes "TypeError". This distinction lets you do different work in the catch block based on the error type. The error object also has a stack property; this is the stack trace showing where the error came from, and is very useful for debugging.
Exercise Create and throw an Error object
Define a function called validateEmail. It should take an email parameter. In the body check with if (!email.includes("@")); when the condition holds call throw new Error("Invalid email"). Then call this function inside a try block as validateEmail("test"); in a catch (e) block call console.error(e.name, e.message).
Show example solution
function validateEmail(email) {
if (!email.includes("@")) {
throw new Error("Invalid email");
}
}
try {
validateEmail("test");
} catch (e) {
console.error(e.name, e.message);
}
Test yourself
-
What is the default value of an Error object's name property?
const err = new Error("X");
console.log(err.name);
- "Error"
- "Exception"
- "TypeError"
- "Unknown"
Show answer
"Error" — Correct. A new Error object's name property defaults to "Error".
-
Create an Error object
const err = ____("Invalid input");
console.log(err.message);
Show answer
const err = new Error("Invalid input");
console.log(err.message);
-
Match Error properties to their meaning
- err.message
- Error text
- err.name
- Error type name
- err.stack
- Stack trace
- new Error("X")
- New error object
Next lesson: The finally block