Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

avoiding 500 TypeError

avoiding 500 TypeError

Problem

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.

Problem courtesy of: john smith

Solution

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.

Solution courtesy of: dsh

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

avoiding 500 TypeError

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×