简体   繁体   中英

Troubles with nodejs GET endpoint

I have the following endpoint:

app.get('/users/:id', async (req, res) => {
const _id = req.params.id;
try {
    const user = await User.findById(_id);

    if(!user) {
        res.status(404).send();
    }

    res.send(user);

} catch (e) {
    res.status(500).send(e);
}});

When I make the request with a valid user ID, the server sends back the user, no problem with that.

The problem is when I try to find a user with a ID which doesnt exist in the database. The server should response with a 404 Error but instead it sends back a Error 500 and I dont understand why!

Could anyone help me please?

Thank you in advance!

One nice way to handle the errors is to create an express error middleware , this allows you to put all of your error handling in one place so that you dont have to write it more than once.

With express when you use async routes handlers if a promise rejects the error will automatically be passed to the next error middleware.

// First register all of your routes
app.get('/user/:id', async (req, res) => {
  const user = await User.findById(req.params.id);
  if(!user) return res.status(404).send();
  res.send(user);
})

// Then register you error middleware 
app.use((err, req, res, next) => {
  console.error(err.message)
  // if mongoose validation error respond with 400
  if(err.message.toLowerCase().includes('validation failed'))
    return res.sendStatus(400)

  // if moongoose failed because of duplicate key
  if(err.message.toLowerCase().includes('duplicate key'))
    return res.sendStatus(409)

  // if mongoose failed to cast object id
  if(err.message.toLowerCase().includes('objectid failed'))
    return res.sendStatus(404)

  res.sendStatus(500)
})

Thank you for your answers.

I have solved it adding the following to the user model schema:

_id: {type: String}

And adding a return before sending the 404 error:

app.get('/users/:id', async (req, res) => {
const _id = req.params.id;

try {
    const user = await User.findById(_id);

    if (!user) {
        return res.status(404).send();
    }
    res.send(user);

} catch (error) {
    res.status(400).send(error);
}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM