问题描述
我有一个创建条目的mysql语句,它具有一个 .then
函数和一个 .catch
函数,但是当发生以下错误时:
I have a mysql statement that creates an entry, it has a .then
function and a .catch
function, but when the following error occurs:
TypeError('绑定参数不能包含未定义.要传递SQL NULL,请指定JS null');
服务器崩溃,而不是回答 .catch
函数
the server crashes instead of answering a 500 like defined in the .catch
function
注意:我使用的是npm中的 mysql2
库,并带有promises( require('mysql2/promise');
)
Note: I'm using the mysql2
library from npm with promises (require('mysql2/promise');
)
这是调用它的代码( req.params.account_name
是 undefined
):
Here's the code that calls it (req.params.account_name
is undefined
):
const CREATE_ACCOUNT_STATEMENT =
'INSERT INTO `Accounts` (`account_token`, `account_name`) VALUES (?, ?)'
try {
mysqlConnectionPool.execute(CREATE_ACCOUNT_STATEMENT, [
account_token, account_name
])
.then(() => {
res.end(JSON.stringify({ token: account_token }))
})
.catch((e) => {
debug(1, "error while trying to create account:", e)
res.status(500).end("Internal Server Error")
})
} catch(e) {
debug(1, "error while trying to create account:", e)
res.status(500).end("Internal Server Error")
}
推荐答案
实际上,@ Quentine接近正确的东西...
Actually, @Quentine was close to the right thing...
这是一类"的 mysql2
中的一个错误,我使用sort-of,因为 https://github.com/sidorares/node-mysql2/issue/902 建议 mysql2
的开发团队可以
It is "sort of" a bug in mysql2
,i use sort-of because https://github.com/sidorares/node-mysql2/issues/902 suggests the development team of mysql2
is o.k. with it.
这是mysql2.pool将调用传递给创建的连接的方式的问题,该方式不会将异常传递给包装的承诺.
it is an issue with the way mysql2.pool passes the call to the created connection, which does not pass the exception to the wrapping promise.
我最终制作了自己的包装函数来创建连接+调用执行,并包装在正确的promise处理中.
I ended up making my own wrapping function to create the connection + call execute wrapped in proper promise handling.
import mysql = require('mysql2');
private async queryDB(query:string, useExecute: boolean = false, ...args:any[]) : Promise<any[]>
{
return new Promise<any[]>((resolve, reject)=>{
for(var i = 0; i < args.length; ++i)
{
if(args[i]===undefined)
args[i] = null;
}
this.dbPool.getConnection((err, conn)=>{
if(err){
reject(err);
return;
}
let cb = function(err: mysql.QueryError, results: any[], fields: mysql.FieldPacket[]) {
conn.release();
if(err)
{
reject(err);
return;
}
resolve(results);
}
if(useExecute)
conn.execute(query, args, cb);
else
conn.query(query, args, cb);
});
});
}
这篇关于为什么这个mysql错误会导致nodejs崩溃而不是转到catch函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!