how do i handle casting errors in mongoose?

here is my function to do that.

const castErrorDB = err => {
  if ( === '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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top