Node.jserror handling – 如何处理未定义的值导致错误

以此URL为例: https : //api.eveonline.com/eve/CharacterID.xml.aspx?names=Khan

使用xml2js node.js模块,你可以parsingXML,虽然看起来不太漂亮:

var CharacterID = response.eveapi.result[0].rowset[0].row[0].$.characterID; 

该应用程序在运行2周后崩溃,全部因为rowset [0]未定义。 在此之前,它因为eveapi没有被定义而崩溃。 真的,我的if-else是否必须像这样才能防止服务器崩溃,由于愚蠢的未定义的对象错误?

  if (!response.eveapi || !response.eveapi.result[0] || !response.eveapi.result[0].rowset[0] || !response.eveapi.result[0].rowset[0].row[0]) { return res.send(500, "Error"); 

除了明显的if (err) return res.send(500, "Error"); error handling在适用的情况下, 未定义错误的一般做法是什么?

正如你所发现的,undefined本身不是一个错误,但是使用undefined作为数组/对象是一个错误。

 x = {'a': { 'b': { 'c': { 'd': [1,2,3,4,5]} } } } ; try { j = xabce[3] } catch(e) { console.log(e); } 

版画

 [TypeError: Cannot read property '3' of undefined] 

这向我build议try / catch可以和你的代码一起使用来返回一个错误代码,如果需要的话,还可以包含一个错误文本(或者把错误文本粘贴到console.log,数据库或本地文件中)。

就你而言,这可能看起来像:

 var CharacterID; // can't define it yet try { CharacterID = response.eveapi.result[0].rowset[0].row[0].$.characterID; } catch(e) { // send description on the line with error return res.send(500, "Error: NodeJS assigning CharacterID: "+e); // return res.send(500, "error"); use this one if you dont want to reveal reason for errors } // code here can assume CharacterID evaluated. It might still be undefined, though. 

我为这种东西写了一个库,叫做dotty( https://github.com/deoxxa/dotty )。

在你的情况下,你可以这样做:

 var dotty = require("dotty"); var CharacterID = dotty.get(response, "eveapi.result.0.rowset.0.row.0.$.characterID"); 

在path不可parsing的情况下,它只会返回undefined。

也许这个function有帮助?

 function tryPath(obj, path) { path = path.split(/[.,]/); while (path.length && obj) { obj = obj[path.shift()]; } return obj || null; } 

对于你的代码,你会使用:

 if (tryPath(response,'eveapi.result.0.rows.0.row.0') === null) { return res.send(500, "Error"); } 

jsFiddle的例子
jsFiddle同样的例子,但作为Object.prototype扩展