Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing Node TypeError crashing app

Using the simple request.js http client I've noticed that sometimes a simple TypeError can crash the whole node app. Taking one of the examples:

request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
       console.log(body) // Print the google web page.
    }
})

Now, take the hypothetical (in Google's case!) situation where Google fails to respond and the connection just hangs then times out. This code simply crashes the node app as response is undefined so response.statusCode cannot be read. This bubbles up to the event loop and triggers the crash with error:

TypeError: Cannot read property 'statusCode' of undefined

What's the simplest way I can prevent this from happening? I could add a check for the value of error before checking for the statusCode for example:

request('http://www.google.com', function (error, response, body) {
    if (!error) {
        if (response.statusCode == 200) {
          // do stuff
        }
    }
})

But I'd rather not add unnecessary lines to the app if possible. I may be missing something obvious here! Any pointers greatly appreciated. Thanks.

like image 420
cud_programmer Avatar asked Oct 02 '22 01:10

cud_programmer


1 Answers

Short answer: This is what you get. Verbose answer:

  • Always check for errors
  • Always check your data

So, something like this is pretty OK:

if (!error && body) {
  //do whatever you want with your body
}

if (!error && response) {
  //do whatever you want with response
}

You have to ensure that object exists before trying to access it(in cases where existence of object is not guaranteed). Also, take a look at maybe2 module. With this module you can write somethis like that:

if (!error && maybe(response).getOrElse({}).statusCode == 200) {
  //your code here
}
  • Use node.js cluster mode, supervisor modules like forever and/or load balancing proxy like nginx in front of your app. This way, if one request fails other requests would be fulfilled by other instances of your app.
  • Be prepared to handle errors at client side and repeat requests on fail.
like image 174
mynameisdaniil Avatar answered Oct 13 '22 10:10

mynameisdaniil