NodeJS Try-Catch not blocking



当json.parse()失败时,应抓住并res.end.end()应终止客户端请求。但是,循环仍以某种方式执行,导致typeError。为什么要达到这一点?好像try-catch块是异步的,因此标题。

const express = require('express');
const http = require('http');
app.get('/', (req, res) => {
    var options = {
        host: 'www.example.com'
    };
    var i = 0
    while (i < 5){
        i++;
        http.get(options, function(resp) {
            var body = '';
            resp.on('data', function(chunk) {
                body += chunk;
            });
            resp.on('end', function() {
                try{
                    var j = JSON.parse(body); // Body will ocasionally be non-json
                }catch(e){
                    res.end("JSON couldn't parse body"); // This should terminate the main request
                }
                for(let item of j.list){
                    console.log(item); // This block sholdn't execute if try-catch fails
                }
            });
        });
    }
});

...

try{
  var j = JSON.parse(body); // Body will ocasionally be non-json
}catch(e){
    res.end("JSON couldn't parse body"); // This should terminate the main request
    return; // <<<<<
}

...

如果JSON.PARSE(身体)抛出异常,您还需要捕获J.LIST的for for for for J.List的例外,请将其放在尝试块中:

        resp.on('end', function() {
            try{
                var j = JSON.parse(body); // Body will ocasionally be non-json
                for(let item of j.list){
                    console.log(item); // This block sholdn't execute if try-catch fails
                }
            }catch(e){
                res.end("JSON couldn't parse body"); // This should terminate the main request
            }

        });

最新更新