当JSON.parse()失败时,应该捕获它,res.end()应该终止客户端请求。但for循环仍以某种方式执行,导致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
}
});
});
}
});
答案 0 :(得分:1)
...
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; // <<<<<
}
...
答案 1 :(得分:0)
如果JSON.parse(body)抛出异常,你还需要捕获j.list的for循环的异常,把它放在try块中:
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
}
});