在发送HTTP响应之前捕获mysql错误 [英] catch mysql errors before sending HTTP response

查看:85
本文介绍了在发送HTTP响应之前捕获mysql错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自php后台,其中sql查询被阻止.

I am coming from php background where sql queries are blocking.

我通常的设置是制作一个 try,catch 块,以处理表更新期间可能发生的任何可能的错误.我想将这种逻辑转移到nodejs,但是它的异步特性使它变得很麻烦.看一下示例代码:

My usual setup is to make a try, catch block to handle any possible errors that might happen during table updating. I wanted to transfer this logic to nodejs, but it's asynchronous nature is making this troublesome. Take a look at example code:

var httpServer = Https.createServer(httpsOptions, function (request, response) {


try {
     //many queries in if-else, switch statements
     if(something){
     mysqlConnection.query(query,[],function(err, result){});
     }else{
     //many queries will follow
       if(somethingelse){
        mysqlConnection.query(query2,[],function(err, result){});
       }else{
        mysqlConnection.query(query3,[],function(err, result){});
          if(andsoon){}
       }
     }

     response.writeHead(200, { "Content-Type": "text/plain" });
     response.end("Got it.");
     console.log("Response successful");
}catch(error){
     console.error(error);
     response.writeHead(400, { "Content-Type": "text/plain" });
     response.end("Error.");
}

}).listen(8000);

因此, response.end()将在查询执行之前触发,因此我会在知道查询是否成功之前发送消息.我可以将 response.end()代码包装在回调中,但是有许多查询正在执行,所以现在我必须跟踪到目前为止已执行了多少个查询.情况变得更糟,1个if-else控制流仅需要1个查询,而其他一些则需要10个查询,因此在代码完成时进行跟踪会产生疯狂的开销.

So, response.end() will trigger before the query executes so I send the message before I know if the query was successful. I could wrap the response.end() code in callback, but there are MANY queries that are executing, so now I have to track how many were executed so far. Things get worse, 1 if-else control flow requires just 1 query, some other requires 10 so there is crazy overhead with tracking when the code is completed.

这都不是最佳的工作流程.如果您有一个复杂的查询系统,并且只想在所有查询都已执行(或失败)后才发送响应,该怎么办?

This all can't be the optimal workflow. What do you do when you have a complex query system and you want to send response only after all queries have executed(or failed)?

推荐答案

您已从.query调用中放入了null回调.那是你的问题.

You've put null callbacks from your .query invocations. That's your problem.

mysqlConnection.query(query,[],function(err, result){});
                               xxxxxxxxxxxxxxxxxxxxxxxx

JavaScript继续运行显示的之后的下一条语句,而无需等待查询完成.您知道仅当.query方法调用您的回调函数时,查询才完整(或遇到错误).

Javascript goes on to run the next statement after the one shown immediately without waiting for the query to finish. You know the query is complete (or it hit an error) only when the .query method invokes your callback function.

因此,您需要执行类似的操作.

So, you need to do something like this instead.

mysqlConnection.query(query,[],function(err, result){
    if (err) throw Error(err);
    //many queries will follow
    if(somethingelse){
           ...
    }
});

像您需要的一系列查询最终以一组荒谬的深度嵌套的回调函数结束.但是请不要失望:Javascript的Promise模式可为您解决此问题,并为您提供简洁的代码.使用 npm的promise-mysql软件包.并编写这样的代码.

A sequence of queries like you need ends up with an absurdly deeply nested set of callback functions. But don't despair: Javascript's Promise pattern works around this for you and gives you clean code. Use npm's promise-mysql package. And write code like this.

    mysqlConnection.query(query,[])
    .then (function(mySqlConnection) {
         if (somethingelse) 
             return mysqlConnection.query(query2,[]) 
         else
             return mysqlConnection.query(query3,[]) 
         })
     .then (function(mySqlConnection) {
          return mysqlConnection.query(query4,[]) 
         })
     .then (function(mySqlConnection) {
          response.writeHead(200, { "Content-Type": "text/plain" });
          response.end("Got it.");
         })
     .catch (function(err)) {
          /* failure somewhere ! */
         });

您有一系列的then函数,最后有个陷阱.Promise子系统为您隐藏了所有回调调用,而是以这种方式进行组织.(请注意,我没有调试此示例代码.)

You have a series of then functions, with a catch at the end. The Promise subsystem hides all the callback invocation for you, organizing it this way instead. (Notice that I did not debug this sample code.)

您必须弄清楚承诺的东西成功编程sql/nodejs.起初这是违反直觉的(至少在我学习时是对我来说).但这值得您的努力.专家提示:如果要在调试器中逐步执行此类代码,请自由使用逐步进入".

You must figure out this Promise stuff to program sql / nodejs successfully. It's counterintuitive at first (at least it was for me when I was learning it). But it's worth your effort. Pro tip: if you're stepping through this kind of code in a debugger, use Step Into liberally.

这篇关于在发送HTTP响应之前捕获mysql错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆