I have actually made an error handler to handle the status code errors and display a message accordingly but it is giving me the following error:
const castError = new CastError();
^
CastError: Cast to ObjectId failed for value "636e6099887452407c7551e" (type string) at path "_id" for model "Product"
at model.Query.exec (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\query.js:4891:21)
at model.Query.Query.then (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\query.js:4990:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
messageFormat: undefined,
stringValue: '"636e6099887452407c7551e"',
kind: 'ObjectId',
value: '636e6099887452407c7551e',
path: '_id',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
at new BSONTypeError (D:\Abdullah's Data\Ecommerce Project\node_modules\bson\lib\error.js:41:28)
at new ObjectId (D:\Abdullah's Data\Ecommerce Project\node_modules\bson\lib\objectid.js:67:23)
at castObjectId (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\cast\objectid.js:25:12)
at ObjectId.cast (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\schema\objectid.js:246:12)
at ObjectId.SchemaType.applySetters (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\schematype.js:1201:12)
at ObjectId.SchemaType._castForQuery (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\schematype.js:1648:15)
at ObjectId.SchemaType.castForQuery (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\schematype.js:1636:15)
at ObjectId.SchemaType.castForQueryWrapper (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\schematype.js:1612:20)
at cast (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\cast.js:342:32)
at model.Query.Query.cast (D:\Abdullah's Data\Ecommerce Project\node_modules\mongoose\lib\query.js:5319:12),
valueType: 'string'
error.js file is like the following
const ErrorHandler = require("../utils/errorhandler");
module.exports = (err, req, res, next) => {
err.statusCode = err.statusCode || "500";
err.message = err.message || "Internal Server Error";
res.status(err.statusCode).json({
success: false,
message: err.message
})
}
Error handler file is something like
class ErrorHandler extends Error{
constructor(message, statusCode){
super(message);
this.statusCode = statusCode;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ErrorHandler;
And I am using it inside the productController.js file as
exports.getProductDetails = async (req, res, next)=>{
const product = await Product.findById(req.params.id);
if(!product){
return next(new ErrorHandler("Product not Found", 404));
}
res.status(200).json({
success: true,
product
})
}
If I manually use the req.body method and define the error by myself then it is working fine but if I use error handler then it is causing problems.