Custom Error Classes
Introduction: When Things Go Wrong
In our previous lesson, we learned how to use inheritance to build specialized classes like a SavingsAccount. We saw how the extends keyword allows one class to take on the features of another. While building features is exciting, professional programming also requires us to plan for moments when things do not go as expected. For example, what happens if a user tries to withdraw more money than they have or provides a negative number as an amount?
In this lesson, we will apply our knowledge of inheritance to the built-in JavaScript Error class. We will create a custom DomainError class to handle specific problems in our application logic. By the end of this lesson, you will know how to create your own error types, how to throw them when rules are broken, and how to catch them gracefully so your program keeps running instead of crashing.
Why Built-in Errors Fall Short
By default, JavaScript provides a generic Error object. You can create one by saying new Error("Something went wrong"). This is fine for simple scripts, but in a large application, a simple text message is often not enough. If your code receives an error, it is very difficult to write logic that reacts differently to "Insufficient funds" versus "Database connection lost" if both are merely plain text strings.
Professional code needs structured information. We want our errors to carry specific codes or types that our program can read and act upon. This allows us to distinguish between a mistake made by a user and a serious system failure. Rather than merely showing a message, we can use these codes to decide whether to ask the user to try again or alert a developer that the server is down.
Creating A Custom Error Class
Since Error is a built-in class in JavaScript, we can use the extends keyword to create our own version of it. This is a direct application of the inheritance principles we practiced in the previous lesson. When we create our DomainError class, we call super(message) to let the original Error class handle the description. We then add our own properties, like a code, to make the error more useful.
In this example, the constructor takes a message and a specific error code. By setting this.name, we make it clear that this is not merely a standard error, but a specific type we created for our business logic. This custom class will now have all the standard features of an error, such as a "stack trace" that shows where the error occurred, while also carrying our custom code property.
