Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
75
rated 0 times [  80] [ 5]  / answers: 1 / hits: 8394  / 2 Years ago, thu, april 21, 2022, 12:00:00

I'm a beginner.


when i'm testing route with wrong (short) ID, for example instead of "6261220286e8d5e7ee6f221e" i'm putting "6261220286e8d5e7ee6f221" node app crashes with this error:


Screenshot


here is the route code:


router.put('/:id', async (req, res) => {
//Validate with Joi
const { error } = validateGenre(req.body);
//If invalid, return 400 - Bad Request.
if (error) return res.status(400).send(error.details[0].message);
//Look up the genre and Update.
const genre = await Genre.findByIdAndUpdate(req.params.id, { name: req.body.name }, { new: true })
//If not exists, return 404.
if (!genre) return res.status(404).send('The genre with the given ID was not found');
//Return ubdated genre.
res.send(genre);
});

function validateGenre(genre) {
const schema = Joi.object({ name: Joi.string().min(3).max(50).required() });
return schema.validate(genre);
}

here also Genre schema:


const genreSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50,
}
});

const Genre = new mongoose.model('Genre', genreSchema);

My question is: How to handle this type of error, or how to validate requested ID length to return proper message to the client.


Sorry again, I'm really a beginner and thanks in advance.


More From » node.js

 Answers
13

Have you tried using try catch ??, in catch section you can do response with status 500 and an error message thrown by Genre


[#183] Friday, April 8, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
deanna questions
;