[英]How To Catch Errors When Adding a Field With Knex.JS
我們正在使用knex.js生成和執行SQL。 在將字段添加到現有表中時,我們在捕獲錯誤時遇到了麻煩,並且文檔未涵蓋此特定用例。 嘗試添加重復字段的確會在控制台(VSCODE)中返回錯誤,但是不會在錯誤上調用任何標准事件,因此我們無法將其捕獲在代碼中。 這是代碼:
knex.schema.table(tableName, function(table) {
table.string('test').catch(function(e) {
callback(e)
});
}).then(function(e) {
callback(e);
}).catch(function(e) {
callback(e);
})
這是在VSCODE控制台中返回的:
{ [TypeError: table.string(...).catch is not a function] 'error@context': { accessToken: undefined } }
但是,沒有調用任何回調。 添加字段時,如何檢查錯誤?
UPDATE#1此代碼將調用回調,但顯然沒有任何錯誤信息。 並且,無論如何,控制台中都會出現相同的錯誤:
table.string('test').catch(
callback(null, Lib.returnEvent(false))
);
更新#2不會使用以下代碼調用回調:
knex.schema.table(tableName, function(table) {
table.string('ddd');
}).then(function(e) {
callback(e);
}).catch(function(e) {
callback(e);
})
UPDATE#3在此示例中,調用了第一個回調,但是該函數在后續調用中掛起:
knex.schema.table(tableName, function(table) {
table.string('ddd');
callback(true);
}).then(function(e) {
callback(true, e);
}).catch(function(e) {
callback(false, e);
})
通過切換到Knex回調方法而不是使用promises方法,我能夠解決此問題。 此代碼始終有效:
knex.schema.table(tableName, function(table) {
table.string(tableFieldname);
}).asCallback(function(err) {
if (err) {
callback(false, err);
} else {
callback(true);
}
})
這對我有用
return knex('users')
.insert({
username: req.body.username,
password: hash,
})
.returning('*')
.bind(console)
.then(console.log)
.catch(console.error);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.