How to generally handle exceptions?

Michael Ströder michael at stroeder.com
Wed Oct 24 14:41:02 CEST 2001


Nick Bower wrote:
> 
> thanks - i was having trouble knowing where this "desc" field was.  so i
> se now that it is:
> 
> except _ldap.LDAPError, e
>   print 'Your error is ' + e[0]['desc']
> 
> thanks for the help.

Sometimes you can't rely on the exact data structure with e.args
being a dictionary of the form {'desc':'','info':''}. I'd also
recommend to display the info field. E.g. recent versions of
OpenLDAP 2 give more information about schema violation which is
useful for the user.

Maybe it's overkill how web2ldap does it but take the snippet below
as food for thought. Note that web2ldap trys to also handle older
versions of python-ldap floating around:

LDAPError = ldap.LDAPError

[..]

    except LDAPError,e:
      if __debug__:
        w2lapp.core.log_exception(errfile,sid,command,form,ls,env)
      try:
        if type(e.args[0])==type({}):
          ErrMsg = '%s: %s' %
(e.args[0]['desc'],e.args[0].get('info',''))
        elif type(e.args[0])==type(1):
          ErrMsg = 'Error Code: %d<br />Error description: %s' % (
            e.args[0],e.args[1]
          )
        else:
          ErrMsg = str(e.args)
      except TypeError:
        ErrMsg = str(e.args)
      except IndexError:
        ErrMsg = str(e.args)
      w2lapp.gui.ExceptionMsg(
        sid,outf,form,ls,'LDAP exception',ErrMsg
      )

[..]

Ciao, Michael.




More information about the python-ldap mailing list