Node.js 错误处理——如何处理导致错误的未定义值

Sah*_*bov 5 javascript error-handling node.js xml-parsing express

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

使用xml2js node.js 模块,您可以解析该 XML,尽管它看起来不太漂亮:

var CharacterID = response.eveapi.result[0].rowset[0].row[0].$.characterID;
Run Code Online (Sandbox Code Playgroud)

该应用程序在运行 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");
Run Code Online (Sandbox Code Playgroud)

除了适用的明显错误处理之外,未定义if (err) return res.send(500, "Error");错误的一般做法是什么?

Pau*_*aul 3

正如您所发现的,未定义本身并不是一个错误,但使用未定义作为数组/对象是一个错误。

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

印刷

[TypeError: Cannot read property '3' of undefined]
Run Code Online (Sandbox Code Playgroud)

这对我来说意味着 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.
Run Code Online (Sandbox Code Playgroud)