Web Form Error Handling Techniques

Sean Abrahams sa at sfsu.edu
Fri Jan 16 12:53:47 EST 2004


The following is a reprint of a message I sent to the tutor list a long 
time ago, that I haven't gotten around to discussing with anyone else 
and failed to hear a reply on the tutor list. Hoping someone here may 
want to have some dialog.

--

I'm learning to write unit tests and am trying to write them for a web
application I'm working on.

I'm currently writing a test that is to purposefully fail by passing
invalid data to a function. However this brought me to thinking about
how to handle errors.

Let me set up a hypothetical scenario.

I have a web form with name and age as its two fields. When a person
enters his/her information and submits the form, I take the two fields
and create a dict that contains {'name' : 'Foo', 'age' : '82'}.

I pass this information to a function called, insertData which
looks something like this:

def insertData(data):

     # test data for validity
     if not data['name'].isalpha():
        raise InvalidDataError(data['name'], "Name contains non-alpha
        characters")
     if not data['age'].isdigit():
        raise InvalidDataError(data['age'], "Age contains non-digit
        characters")

     sql = """
     INSERT INTO people (name, age) VALUES ('%s', '%s')
     """ % (data['name'], data['age'])

     executeSQL(sql)

I should first check to see if the data is valid, meaning that the
name contains only alpha characters and the age only containing
numeric characters.

If I raise an exception, how would one handle the reprinting of the
web form with a red * next to the field that contains invalid data? If
one field is in error, I can see that upon receiving an exception you
can have your code just reprint the web form with the red star, but
what about when both fields are in error, do you have the exception
create a list which then your code checks to see if it exists and then
loops through it to know what fields are in error?

And then again, perhaps I'm completely wrong and am going about this
in an amateur manner.

I realize this is more of a style question, but that's what I'm
interested in discussing.

Thanks,
--Sean





More information about the Python-list mailing list