2016-10-07 61 views
1

我爲我的web應用程序使用了sa風格的js。我必須改變beforeCreate的默認行爲。首先看一下代碼:之前創建js創建next()回調

beforeCreate: function(values, next) { 

    //ParamsCheck is my service and 'check' is method which will validate the 
    //parameters and if any invalid parameter then error will be thrown, otherwise 
    //no error will be thrown 

    ParamsCheck.check(values) 
    .then(() => { 
    // All Params are valid and no error 
    next(); 
    }) 
    .catch((err) => { 
    //Some errors in params, and error is thrown 
    next(err); 
    }); 
} 

那麼,問題是,如果有任何錯誤,那麼下一個方法被自動重定向到SERVERERROR,錯誤代碼500,而我想這與我的自定義響應重定向(如: badRequest,err code 400)。如何實現這一目標?

+0

你是如何發送收到此錯誤後的反應,可以顯示在那裏稱爲最終回調的代碼? – abdulbarik

+0

其實在sails中,如果有任何參數傳遞給beforeCreate方法的next()回調函數,那麼它會出錯,我們會得到500錯誤。 'next()'是最後的回調。我想更改默認響應。 –

+0

每當你通過錯誤回調,它會給你500 statusCode.For錯誤的請求意味着statusCode:400你需要通過,當你響應客戶端 – abdulbarik

回答

1

您正在執行某種驗證beforeCreate。但是,這不是驗證的正確位置。

更好的方法是使用這裏描述的自定義驗證規則http://sailsjs.org/documentation/concepts/models-and-orm/validations#?custom-validation-rules或創建一個策略來處理驗證。

我喜歡用政策:

module.exports = function(req, res, next) { 
    var values = req.body; 
    ParamsCheck.check(values).then(() => { 
    return next(); 
    }).catch((err) => { 
    return res.send(422); // entity could not be processed 
    }); 
};