2017-01-11 24 views
0

我試圖處理所需的驗證錯誤,從而使錯誤消息更可讀的被傳遞到前端之前:爲什麼不是貓鼬自定義錯誤處理工作不

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); 
    } 
    }); 

此代碼會導致用戶當academicRole屬性丟失時,保存回調以使錯誤成爲空對象;爲什麼不使用包含自定義消息的錯誤對象調用保存回調?

回答

0

驗證錯誤應該在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); 
    } 
    }); 
+0

使用該代碼,不記錄任何內容。 Mongoose的文檔似乎也表明錯誤是在錯誤處理中間件後保存後處理的。 –

+0

我只看了一下文檔。它表示 - 「*驗證是異步遞歸的;當您調用Model#save時,也會執行子文檔驗證。如果發生錯誤,則您的Model#保存回調會收到*」。據我所知,這意味着錯誤不會出現在'post('validate')'或'post('save')'鉤子中。它實際上會顯示在'save()'方法本身中。請參閱[文檔在這裏](http://mongoosejs.com/docs/validation.html)。 –

+0

post validate沒有被調用的問題可能是我正在驗證的值是'undefined',這個副本只能通過內置的'required'驗證器來驗證,這是我試圖攔截的驗證器。 –