Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Take this URL for instance: https://api.eveonline.com/eve/CharacterID.xml.aspx?names=Khan

Using xml2js node.js module you may parse that XML, although it does not look pretty:

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

The app crashed after 2 weeks of running, all because rowset[0] was undefined. Prior to that it crashed because eveapi was not defined. Seriously, does my if-else has to be like this just to prevent server from crashing due to stupid undefined object errors?

 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");

Besides the obvious if (err) return res.send(500, "Error"); error handling where applicable, what is the general practice for undefined errors?

like image 416
Sahat Yalkabov Avatar asked Feb 17 '23 02:02

Sahat Yalkabov


1 Answers

I wrote a library for this kind of thing, called dotty (https://github.com/deoxxa/dotty).

In your case, you could do this:

var dotty = require("dotty");

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

In the case of the path not being resolvable, it'll just return undefined.

like image 133
deoxxa Avatar answered Feb 18 '23 18:02

deoxxa