Javascript error read errors

Custom errors, extending Error

When we develop something, we often need our own error classes to reflect specific things that may go wrong in our tasks. For errors in network operations we may need HttpError , for database operations DbError , for searching operations NotFoundError and so on.

Our errors should support basic error properties like message , name and, preferably, stack . But they also may have other properties of their own, e.g. HttpError objects may have a statusCode property with a value like 404 or 403 or 500 .

JavaScript allows to use throw with any argument, so technically our custom error classes don’t need to inherit from Error . But if we inherit, then it becomes possible to use obj instanceof Error to identify error objects. So it’s better to inherit from it.

As the application grows, our own errors naturally form a hierarchy. For instance, HttpTimeoutError may inherit from HttpError , and so on.

Extending Error

As an example, let’s consider a function readUser(json) that should read JSON with user data.

Here’s an example of how a valid json may look:

Internally, we’ll use JSON.parse . If it receives malformed json , then it throws SyntaxError . But even if json is syntactically correct, that doesn’t mean that it’s a valid user, right? It may miss the necessary data. For instance, it may not have name and age properties that are essential for our users.

Our function readUser(json) will not only read JSON, but check (“validate”) the data. If there are no required fields, or the format is wrong, then that’s an error. And that’s not a SyntaxError , because the data is syntactically correct, but another kind of error. We’ll call it ValidationError and create a class for it. An error of that kind should also carry the information about the offending field.

Читайте также:  Python count word frequencies

Our ValidationError class should inherit from the Error class.

The Error class is built-in, but here’s its approximate code so we can understand what we’re extending:

// The "pseudocode" for the built-in Error class defined by JavaScript itself class Error < constructor(message) < this.message = message; this.name = "Error"; // (different names for different built-in error classes) this.stack = ; // non-standard, but most environments support it > >

Now let’s inherit ValidationError from it and try it in action:

Источник

Оцените статью