How to handle a Python BadKeyError exception in Google AppEngine at paulcarvill.com, the home of Paul Carvill on the web

link: paulcarvill on twitter

link: paulcarvill at flickr

paulcarvill.com

Hi, I'm Paul Carvill, I'm a web developer. I'm currently working as Technical Lead at LBi, Europe's largest digital agency.

I also like walking, cooking, Bollywood and rock 'n' roll.

How to handle a Python BadKeyError exception in Google AppEngine

posted: Tuesday, June 1st, 2010 at 11:16 pm

This drove me nuts an hour tonight. If you’re trying to get an entity key using something like:

yourKey = someString
candidate = Candidate( key=db.Key(yourKey) )

and you get a BadKeyError, it’s because the string you’re sending in isn’t the right length. Also, AppEngine doesn’t return None from the Key method but instead returns a BadKeyError exception. You can handle this by doing:

yourKey = someString
try:
   candidate = Candidate( key=db.Key(yourKey) )
except db.BadKeyError:
   # handle the exception here

Tags:

Comments are closed.