Home > Software engineering >  Mongoose - Difference between Error.ValidationError, and Error.ValidatorError
Mongoose - Difference between Error.ValidationError, and Error.ValidatorError

Time:06-11

The question pretty much says it all.

As far as I can tell from the docs, one is for general validation errors (a required field not being included, maxLength being exceeded, etc.).

And one is given as the reason within the other, whenever an error occurs within a custom validator... Is that correct?

If so, which is which? The naming convention used is really confusing here!

CodePudding user response:

After a little more research, and investigation. It seems that all validation type errors (which include Error.CastError errors) always exist within a, Error.ValidationError object. This is the parent object, and itself doesn't really offer much information, other than that validation has failed somewhere along the line.

Within this Error.ValidationError object, can be many other error objects. It's these children that will be instances of Error.ValidatorError (or Error.CastError).

A validation error will therefore look something like:

// When receiving some error, with the variable name "err".
err instanceof mongoose.Error.ValidationError
// true

console.log(err);
errors: {
  some_doc_field_name: {}     // Possibly an instanceof "Error.ValidatorError"
  another_doc_field_name: {}  // Possibly an instanceof "Error.CastError"
}

TL;DR:

  • ValidationError = the parent type of the error.
  • ValidatorError = one of the potential children types of error it's children can have.
  • Related