2017-09-29 1 views
0

Wenn JSON.parse() fehlschlägt, sollte es abgefangen werden und res.end() sollte die Client-Anforderung beenden. Aber die for-Schleife wird immer noch irgendwie ausgeführt, was einen TypeError verursacht. Warum erreicht es diesen Punkt? Es ist, als wäre der try-catch-Block asynchron, daher der Titel.NodeJS Try-Catch blockiert nicht

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 
       } 

      }); 
     }); 
    } 

}); 
+2

'Dieser Block sholdn't ausführen, wenn try-catch fails' es innerhalb des Blocks dann versuchen, setzen ... oder' return res.end ("JSON konnte nicht Parsen Körper ");' –

Antwort

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

...

+0

Oooh, ich dachte res.end() zurückgegeben. (: Vielen Dank! – spikes

0

Wenn die JSON.parse (Körper) throw Ausnahme, müssen Sie auch die Ausnahme von der for-Schleife von j.list zu fangen, steckt es in dem try-Block:

 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 
      } 


     });