Beside Error Handling, Creating Errors with Error Objects Is Equally Important

Beside Error Handling, Creating Errors with Error Objects Is Equally Important

Daily short news for you
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

    » Read more

The Issue

A while ago, I wrote an article on Error Handling Techniques in Node.js, focusing on how to catch errors and handle them effortlessly. In this article, we'll temporarily set aside those techniques and dive deep into the topic of "throwing" errors and how to "catch" them effectively.

I believe many of us, including myself, have thrown an error that looks like this:

function login(username, password) {
  // code
  if (password != hash_password) {
    throw new Error("Password is incorrect");
  }
// code
}

Then we "catch" the error:

try {
  login("admin", "123456");
} catch(e) {
  console.log(e.message);
  // logic handle
}

There's not much to discuss about error handling in the code above. When you "throw" an Error, it carries a lot of useful information causing the error, such as the stack trace and error message. Therefore, e in catch(e) helps us easily trace the origin of the error for proper handling.

I've encountered cases where errors were thrown incorrectly, instead of using new Error, a string or an object was thrown. Something like:

throw 'Password is incorrect';

With this approach, we can still use try catch. However, e in this case is simply a string or an object that you threw earlier, lacking important information like stack trace and message as in Error. That's why, whenever you throw an error, it should be turned into an instance of Error.

Error accepts a string parameter, which is also the content of e.message. If you deliberately pass more than one parameter or a parameter that is not a string like an object, it will result in something like this:

throw new Error({ "name": "2coffee" });

VM400:1 Uncaught Error: [object Object]
    at <anonymous>:1:7

I bring up this issue because there are many cases where we need to include additional information in an error for convenient handling of certain logic. For example, besides message, I may need to add uuid as the ID of the record causing the error, detail containing a more detailed description, code to specify the error code defined in the system... and that's impossible with Error.

Is there a way to achieve this?

Errors Class

Error is an object thrown when a runtime error occurs. It can also be used as a base object for errors defined by users. In simpler terms, you can create a class that inherits from Error to create your own error object.

JavaScript provides some "custom" error objects based on Error that you might have encountered many times, such as:

To see a full list of error types, you can refer to Error types - Mozilla.

The commonality among them is that they are based on Error, so they have all the important attributes of Error. Additionally, these errors bring transparency to your code. For example, when throwing a RangeError, we can know that the error is caused by a value that is outside the allowed range, instead of a generic throw new Error('The argument must be between 1 and 10').

To differentiate error objects, you can simply use conditional statements like if...else, switch...case...

if (err instanceof RangeError) {
  // handle RangeError
} else if (err instanceof ReferenceError) {
  // handle TypeError
}
...

These custom error objects are similar to Error, with the only difference being their name. So, if you need a more "distinct" error, let's move on to the next section.

Custom Errors Class

We can define our own types of errors by inheriting from Error. Then, throw an error with throw MyError and use instanceof MyError to check the error type in catch. This leads to cleaner and more consistent error handling code.

The simplest syntax to create a custom MyError:

class MyError extends Error {
  constructor(message) {
    super(message);
    this.name = this.constructor.name;
  }
}

MyError is now assigned the name of constructor.name, which is also the name of the MyError class. However, it doesn't have much difference compared to a regular Error, except for the name. We need to add a few properties like code for error code and statusCode to define HTTP response status codes.

class MyError extends Error {
  code;
  statusCode;

  constructor(message, code, statusCode) {
    super(message);
    this.name = this.constructor.name;
    this.code = code;
    this.statusCode = statusCode;
  }
}

To throw an error, use the syntax throw MyError:

try {
  throw new MyError("My error message", 123, 404);
} catch (err) {
  console.log(err.name, err.message, err.code, err.statusCode);
  // MyError My error message 123 404
}

With this feature, you can create many custom errors for your specific handling purposes. For example, create ApplicationError, DatabaseError, ValidationError, etc., with similar features to system errors, database errors, data validation errors... to hide or display error messages to users.

Conclusion

Error is an object for handling errors in JavaScript programs. The best way to throw an error is to throw an Error instead of a string or another object. JavaScript defines some "custom" error types based on Error, such as ReferenceError, SyntaxError, RangeError... In addition, you can create custom error types by inheriting from Error.

References:

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...