对node.js mysql错误处理感到困惑

发布于 2025-02-12 11:32:58 字数 849 浏览 0 评论 0原文

首先,我对Node.js来说是新手,其处理错误的方式对我来说仍然很陌生。我真的很努力地缠绕着它。

我正在尝试使用Express在Node.js中编写一个简单的程序,该程序通过网络接收MySQL查询,执行它们并返回结果。该部分已经起作用,但是如果客户端发送导致MySQL错误的查询,则该程序会崩溃。有问题的代码块如下所示,在正常(非异步)函数内部:

try {
    connection.query(queryFromClient, function (error, result, field) {
        if (error) {throw error} else {
            response.send(result[0]);
            response.status(200); 
        };
    })
} catch (error) {
    response.send("Query error");
    response.status(422);
    console.log("Query error from client");
    }
});

如您所见,查询应该如果出了问题,则会丢弃错误,并且该错误包裹在一个“尝试”语句。正确形成的查询可以正常工作,但是畸形的查询使该程序在连接上崩溃。例如,如果我运行从BadTable中选择列,而数据库中不存在BadTable,则我在客户端端没有响应,并且Node.js log:

throw err; // Rethrow non-MySQL errors
^

Error: ER_NO_SUCH_TABLE: Table 'mydb.badtable' doesn't exist

First of all, I'm fairly new to node.js and its way of handling errors still feels foreign to me. I'm just really struggling to wrap my head around it.

I'm trying to write a simple program in node.js using express that receives mySQL queries over the network, executes them, and returns the result. That part is already functional, but the program crashes if the client sends a query that results in a mySQL error. The offending code block is as follows, inside of a normal (as in not async) function:

try {
    connection.query(queryFromClient, function (error, result, field) {
        if (error) {throw error} else {
            response.send(result[0]);
            response.status(200); 
        };
    })
} catch (error) {
    response.send("Query error");
    response.status(422);
    console.log("Query error from client");
    }
});

As you can see, the query should throw an error if something goes wrong, and that error is wrapped in a "try" statement. Properly formed queries work okay, but malformed queries cause the program to crash on the connection.query line despite the error handling. If, for instance, I run SELECT column FROM badtable, where badtable doesn't exist in the database, I get no response on the client end and the following error in the node.js log:

throw err; // Rethrow non-MySQL errors
^

Error: ER_NO_SUCH_TABLE: Table 'mydb.badtable' doesn't exist

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她如夕阳 2025-02-19 11:32:58

您可以创建一个错误函数:

(err, req, res, next) => {
   return res.status(err.statusCode).json({ message: err.msg })
 }

而不是将错误传递给“下一个”函数

if (error) {
    next(error)
    return
}

You can create an error function:

(err, req, res, next) => {
   return res.status(err.statusCode).json({ message: err.msg })
 }

And instead of throwing the error pass it to the "next" function

if (error) {
    next(error)
    return
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文