How to handle for Cast Errors in MongoDB/mongoose

Viewed 1113

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.

2 Answers

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

Into my project I have something like this. Maybe can help you to get any idea:

try{
  //mongoose query
}catch(e){
  if(e.name === 'MongoError' && e.code === 11000){
    //Duplicate ID error
  }else if(e.name == 'CastError'){
    if(e.reason.toString()
         .startsWith('Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters')){
      //Bad ID format error
    }else{
      // General CastError
    }
   }else{
    //General error message
  }
}
Related