express-async-handler icon indicating copy to clipboard operation
express-async-handler copied to clipboard

express-async-handler didn't give the exact form of error I want

Open iamAravindks opened this issue 4 years ago • 1 comments

when I using the findById method defined by mongoose, I got a Cast error something like this

CastError: Cast to ObjectId failed for value "611411089cb0c839083962ba4" (type string) at path "_id" for model "Product"
    at model.Query.exec (/home/user/web/mern/emartwell/node_modules/mongoose/lib/query.js:4498:21)
    at model.Query.Query.then (/home/user/web/mern/emartwell/node_modules/mongoose/lib/query.js:4592:15)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)

But I need the product not found error.

Code

productRoute.js


import express from "express";
import asyncHandler from "express-async-handler";
import Product from "../models/productModel.js";


const router = express.Router();

router.get(
    "/:id",
    asyncHandler(async (req, res) =>
    {
        const product = await Product.findById(req.params.id);
        if (product)
        {
            res.json(product);
        } else
        {
            res.status(404).send({ message: "Product not found" });
        }
    })
);

export default router;


But using the below code gives the exact output I want

        try
        {
            const product = await Product.findById(req.params.id);
            res.json(product);
        } catch (error)
        {

            res.status(404).json({ message: "Product not found" })
        }

Please help me to get rid of this problem. Thanks in advance :D

iamAravindks avatar Aug 12 '21 13:08 iamAravindks

Your problem is entirely unrelated to this Github repo.

An ObjectId must be exactly 24 hex characters (or 12 bytes, in binary), but your string 611411089cb0c839083962ba4 has 25 characters. https://stackoverflow.com/questions/14940660/whats-mongoose-error-cast-to-objectid-failed-for-value-xxx-at-path-id

You could also implement a custom error handler that transforms the error to your desired response. http://expressjs.com/en/guide/error-handling.html#writing-error-handlers Could go approximately like this, haven't tested it:

app.use(function (err, req, res, next) {
  console.error(err.stack)
  if (err.message && err.message.includes('Cast to ObjectId failed')) {
    res.status(404).send({ message: "Product not found" });
  } else {
    res.status(500).send('Something broke!');
  }
})

heidemn avatar Aug 18 '21 20:08 heidemn