mykeels.com

The JavaScript Error prototype

Today, while playing with the Sequelize ORM, I saw that I was able to get a unique name from the errors thrown by its operations.

The JavaScript Error prototype

Today, while playing with the Sequelize ORM, I saw that I was able to get a unique name from the errors thrown by its operations.

One of them was called SequelizeUniqueConstraintError.

I previously didn’t know it was possible, so while searching the web and stumbling upon this stackoverflow answer, I learned something new about JavaScript Errors, which I’ll share with you.

What I learned

In JavaScript, the Error class prototype has a name variable which is set to Error by default.

You can make custom errors, which becomes useful when you want to know what type a thrown error is.

function NotImplementedError(message) {
   this.name = ‘NotImplementedError’
   this.message = message || ‘’
}

Next, set its prototype to that of Error

NotImplementedError.prototype = Error.prototype

Do something that throws our new NotImplementedError

try{
   // throw error
   throw new NotImplementedError()
}
catch (err) {
   if (err.name === ‘NotImplementedError’) {
      // this error was thrown because a function was executed that hasn’t been implemented
   }
   else {
      // this error was thrown for some other reason
   }
}

Differentiating between errors/exceptions is a feature that is used a lot in typed languages like C#, and is very useful for error handling.

Related Articles

Tags