spikes spikes - 2 years ago 213
Javascript Question

NodeJS Try-Catch not blocking

When the JSON.parse() fails, it should be caught and res.end() should terminate the client request. But the for-loop is still somehow executed, causing a TypeError. Why does it reach that point? It's as if the try-catch block is async, hence the title.

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
}

});
});
}

});

Answer Source

...

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; // <<<<<
}

...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download