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
CLICK HERE to find out more related problems solutions.