使用简单的request.js http客户端时,我注意到有时候一个简单的TypeError
会导致整个节点应用程序崩溃。看一个例子:
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
})
现在,假设(以Google为例)Google未能响应并且连接一直挂起,然后超时。这个代码会简单地使节点应用程序崩溃,因为response
未定义,所以无法读取response.statusCode
。这会冒泡到事件循环并触发错误导致崩溃:
TypeError: Cannot read property 'statusCode' of undefined
我该如何最简单地防止这种情况发生?例如,我可以在检查statusCode
之前先检查error
的值:
request('http://www.google.com', function (error, response, body) {
if (!error) {
if (response.statusCode == 200) {
// do stuff
}
}
})
如果可能的话,我不想在应用程序中添加不必要的行。也许我漏掉了一些显而易见的东西!非常感谢任何指导。谢谢。