Skip to content
Advertisement

How to handle for Cast Errors in MongoDB/mongoose

I am using mongoDB. I don’t like the default error message that is thrown by mongoose/mongoDB. I would like to check for the error type and if it is a cast error then I would like to send a different error message.

Advertisement

Answer

here is my function to do that.

const castErrorDB = err => {
  if (err.name === 'CastError')
    return new Error(`Invalid ${err.path}: ${err.value}`);
  return err;
};

this function take an error and if it was a cast error return a new error with message Invalid ${err.path}: ${err.value}.

if error was not cast error, return original error.

use this function every where you like. but there is a note: if error was a cast error, the result error is different and the stack is not equal to original error

Advertisement