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

Node.js Error Handling -- how to deal with undefined values causing errors

本文关键字:处理 错误 未定义 js 何处理 Node      更新时间:2023-09-26

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

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

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

该应用程序在运行2周后崩溃,这一切都是因为行集[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");错误处理(如适用)外,未定义错误的一般做法是什么?

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

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

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

在路径不可解析的情况下,它只会返回undefined。

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

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

打印

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

这向我建议,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.

也许这个函数有帮助?

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 的扩展