Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

javascript - Error handling with get route with mongoose

router.get('/:id', async (req, res) => {
  const course = await Course.findById(req.params.id);
  if (!course) {
    return res.status(400).send(`course id is invaild`);
  }
  res.send(course);
});

As you guys can see, this is a very simple route function. It works fine if it got the right id but once I gave it the wrong id it throws this error on my console

GET /api/courses/600f4aab118a6c5ef60fb5f7 200 75 - 20.069 ms
(node:32606) UnhandledPromiseRejectionWarning: CastError: Cast to
ObjectId failed for value "600f4aab118a6c5ef60fb5f7a" at path "_id"
for model "Course"
    at model.Query.exec (/home/hesham/Desktop/test-express/node_modules/mongoose/lib/query.js:4358:21)
    at model.Query.Query.then (/home/hesham/Desktop/test-express/node_modules/mongoose/lib/query.js:4452:15)
    at processTicksAndRejections (internal/process/task_queues.js:93:5) 

(Use `node --trace-warnings ...` to show where the warning was created) (node:32606)
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled
with .catch().
To terminate the node process on unhandled promise
rejection, use the CLI flag `--unhandled-rejections=strict` (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).

(rejection id: 1) (node:32606) [DEP0018] DeprecationWarning: Unhandled
promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a
non-zero exit code.
question from:https://stackoverflow.com/questions/65894037/error-handling-with-get-route-with-mongoose

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...