[英]Why isn't mongoose custom error handling not working
我正在嘗試處理所需的驗證錯誤,以使錯誤消息在傳遞給前端之前更具可讀性:
UserSchema
.post('save', function (error, doc, next) {
console.log(error.errors);
if (error.name === 'ValidationError' && error.errors.academicRole.kind === 'required') {
console.log('custom error');
next(new Error('Academic Role is required.'));
} else {
next(error);
}
});
這段代碼會導致用戶的save回調函數被調用,並且當省去了AcademicRole屬性時,該錯誤是一個空對象。 為什么不使用包含自定義消息的錯誤對象來調用保存回調?
驗證錯誤應在post('validate')掛鈎中檢查。
如果存在驗證錯誤,將不會調用save()方法和關聯的鈎子pre('save')和post('save')。
UserSchema
.post('validate', function (err, doc, next) {
console.log(err.errors);
if (err.name === 'ValidationError' && err.errors.academicRole.kind === 'required') {
console.log('custom error');
next(new Error('Academic Role is required.'));
} else {
next(err);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.