[英]Express - Error Handling Doesn't Work with Async Function
所以這是 /products 的 POST 請求,當提交表單時,將調用此 function。 如果表單提交錯誤,我使用 try-catch 來捕獲錯誤。
這是我的架構。
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true,
min: 0
},
category: {
type: String,
lowercase: true,
enum: ['fruit', 'vegetable', 'dairy']
}
});
錯誤與 newProduct.save() 行有關,因此如果我提交一個違反架構的表單,比如沒有名稱,我將收到錯誤消息而不是被重定向到頁面。
app.post('/products', (req, res, next) => {
try {
const newProduct = new Product(req.body);
newProduct.save();
res.redirect(`/products/${newProduct._id}`);
}
catch (e) {
next(e);
}
});
這是我的錯誤處理程序。
app.use((err, req, res, next) => {
const { status = 500, message = 'Something went wrong!' } = err;
res.status(status).send(message);
});
save
方法是異步的,返回一個 promise。在你的例子中, newProduct.save()
返回一個 promise,它沒有被滿足並且實際上沒有拋出錯誤:
app.post('/products', async (req, res, next) => {
try {
const newProduct = new Product(req.body);
await newProduct.save();
res.redirect(`/products/${newProduct._id}`);
}
catch (e) {
next(e);
}
});
最好的解決方案是使用驗證器驗證req.body
並在驗證后保存newProduct
。 最好在保存后返回newProduct
,而不是重定向到某個端點。
如果未通過驗證,您可以拋出自定義錯誤。
我推薦使用非常容易使用的JOI 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.