我是初學者。
例如,當我使用錯誤的(短)ID 測驗路線時,而不是"6261220286e8d5e7ee6f221e"讓"6261220286e8d5e7ee6f221" 節點應用程式崩潰并出現此錯誤:

這是路線代碼:
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);
}
這里還有流派模式:
const genreSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50,
}
});
const Genre = new mongoose.model('Genre', genreSchema);
我的問題是:如何處理此類錯誤,或者如何驗證請求的 ID 長度以向客戶端回傳正確的訊息。
再次抱歉,我真的是一個初學者,提前謝謝。
uj5u.com熱心網友回復:
您是否嘗試過使用try catch??,在 catch 部分中,您可以使用狀態 500 和拋出的錯誤訊息進行回應Genre
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/462409.html
標籤:javascript 节点.js mongodb 猫鼬
