javascript 需要更好的 Node.js http.get 请求错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13401354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:39:30  来源:igfitidea点击:

Need better Node.js http.get request error handling

javascriptnode.js

提问by ttback

I use following http.get()call to call a local endpoint:

我使用以下http.get()调用来调用本地端点:

http.get({
    host: 'localhost',
    port: 80,
    path: '/service/info?id=' + id
}, function(response) {
            console.log(response);
    response.setEncoding('utf8');
    var data = "";

    response.on('data', function(chunk) {
        data += chunk;
    });

    response.on('end', function() {
        if(data.length > 0) {
            try {
                var data_object = JSON.parse(data);
            } catch(e) {
                return;
            }
        }
    });
}).on("error", function (){console.log("GET request error")});

However, if I send a malformed request, which would trigger a HTTP 400, the request is synthetically incorrect etc, even though the response.statusCodein function(response)is 400, it would end up to the catch() response.on('end', function() {}instead of emitting the error event on http.get(), I wonder why that's the case and how i can handle HTTP 400 response as an error on node.js.

但是,如果我发送一个畸形的请求,这会触发一个HTTP 400,请求是综合不正确等,即使response.statusCodefunction(response)是400,这将最终的catch() response.on('end', function() {},而不是上发出错误事件的http.get(),我不知道为什么是这样的话以及我如何将 HTTP 400 响应作为 node.js 上的错误处理。

If it gets to catch(e), it waits a long time till it responses anything to the client, which is also weird. I want the server to respond to the client that it hits a 400 as soon as possible.

如果它到达catch(e),它会等待很长时间,直到它对客户端做出任何响应,这也很奇怪。我希望服务器尽快响应客户端达到 400。

采纳答案by jeremy

response.statusCode contains the status code, you can get that in the http.get(...,cb()) or you can set up a listener

response.statusCode 包含状态代码,您可以在 http.get(...,cb()) 中获取,也可以设置侦听器

    request.on('response', function (response) {}); 

that can get the status code. You can then destroy the request if you want to cancel the GET, or handle it however you want.

可以得到状态码。如果您想取消 GET,则可以销毁该请求,或者根据需要处理它。

回答by modulitos

Elaborating on jeremy's answer, here is an example of checking the status code that works for me:

详细说明 jeremy 的回答,以下是检查对我有用的状态代码的示例:

  http.get(url, function (res) {
    if (res.statusCode != 200) {
      console.log("non-200 response status code:", res.statusCode);
      console.log("for url:", url);
      return;
    }
    // do something great :-)

  });