The Error Constructor
What you'll learn: How to create structured error objects using JavaScript's built-in Error constructor and access their key properties.
What Is the Error Constructor?
When you need to throw an error with meaningful information, JavaScript provides the Error constructor to create standardized error objects. Think of it as a factory for building errors that come with useful metadata attached—like creating labeled packages instead of throwing unmarked boxes.
Creating Error Objects
You create an error using the Error constructor with the new keyword:
const error = new Error("Something went wrong");
The string you pass in becomes the error's message—a human-readable description of what happened.
Key Properties: name and message
Every Error object has two essential properties:
message: The description you provided (or an empty string if none given)name: The type of error, which defaults to"Error"
const error = new Error("File not found");
console.log(error.message); // "File not found"
console.log(error.name); // "Error"
Using Error Objects with throw
You typically create Error objects to throw them:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
try {
divide(10, 0);
} catch (e) {
console.log(e.name); // "Error"
console.log(e.message); // "Cannot divide by zero"
}
This gives you structured, informative errors that catch blocks can inspect and handle appropriately.
Key Takeaway: Use the Error constructor to create error objects with name and message properties, providing clear, structured information about what went wrong in your code.