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.
Short answer: This is what you get. Verbose answer:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With