Isaac
Isaac

Reputation: 840

python ldap.LDAPError object rejects access to dictionary

using python 2.6.5 and python-ldap 2.3.10, I have the following problem: Under certain circumstances my application raises an ldap.LDAPError, or to be more specific, an ldap.INVALID_SYNTAX error. I catch this error and would like to process the message attached to it. Now I can do something like this:

try:
  some_ldap_function(*args,connection=con,**kwargs)
except ldap.INVALID_SYNTAX,e:
  print e

This will give me

{'info': 'feeClass: value #0 invalid per syntax', 'desc': 'Invalid syntax'}

Now this is a dictrionary, and as far as I understand, I should be able to do something like

print e['info']

which is not the case. Instead I get a TypeError Exception: sequence index must be integer, not 'str'

What is wrong here?

Upvotes: 2

Views: 4434

Answers (2)

molostoff
molostoff

Reputation: 61

docs state that

The exceptions are accompanied by a dictionary possibly containing an string value for the key desc (giving an English description of the error class) and/or a string value for the key info (giving a string containing more information that the server may have sent).

so resulting code should look like this:

try:
    ...
except LDAPError, e:
    if 'desc' in e.message:
        print "LDAP error: %s" % e.message['desc']
    else: 
        print e

Upvotes: 3

Martin v. Löwis
Martin v. Löwis

Reputation: 127467

You are misinterpreting what you are seeing

py> e=ldap.INVALID_SYNTAX("{'info': 'feeClass: value #0 invalid per syntax', 'desc': 'Invalid syntax'}")
py> print e
{'info': 'feeClass: value #0 invalid per syntax', 'desc': 'Invalid syntax'}
py> e.args
("{'info': 'feeClass: value #0 invalid per syntax', 'desc': 'Invalid syntax'}",)

So printing e prints e.args[0], which is a string. That string looks like the repr of a dictionary, but that doesn't mean that e is a dictionary (in fact, it should be clear that e can't be a dictionary, since it must be an exception).

Upvotes: 2

Related Questions