cud_programmer
cud_programmer

Reputation: 1264

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.

Upvotes: 5

Views: 2860

Answers (1)

mynameisdaniil
mynameisdaniil

Reputation: 1178

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.

Upvotes: 4

Related Questions