john smith
john smith

Reputation: 561

avoiding 500 TypeError

on node.js, suppose I have an object like this:

var users = {
  '1': { name: 'john' },
  '2': { name: 'jack' },
  '3': { name: 'hal' },
};

If I try to access users['4'].name, I will obviously get a 500 TypeError: Cannot read property 'name' of undefined.

Totally understandable but, what about making it silent? Was it too hard for the node.js developers to implement such feature? Or am I missing some 'security' or whatever issues?

Anyway, is there an easy way to silent the error?

Thanks in advance.

Upvotes: 0

Views: 539

Answers (1)

dsh
dsh

Reputation: 12214

You need to fix your code. Instead of writing users['4'].name, write something like:

if ('4' in users)
    { users['4'].name; }

You need to check every condition in your code that affects your code. The Node.js runtime can't know if you made a mistake or if you simply didn't care to actually execute some statements.

Upvotes: 1

Related Questions