Help catching error message
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Nov 8 17:16:33 EST 2011
On Tue, 08 Nov 2011 05:20:51 -0800, Gnarlodious wrote:
> What I say is this:
>
> def SaveEvents(self,events):
> try:
> plistlib.writePlist(events, self.path+'/Data/Events.plist') #
> None if OK
> except IOError:
> return "IOError: [Errno 13] Apache can't write Events.plist
> file"
>
> Note that success returns"None" while failure returns a string.
I started off writing a sarcastic response about people who refuse to
learn idiomatic Python and instead insist on writing (e.g.) Java or PHPP
in Python. But then I eventually got to the *very last line* of your post
where you noted that you were doing this in WSGI.
For future reference, when writing unidiomatic code *deliberately*,
please say so up front, at the start of your message rather than at the
end, and save your readers (or at least *me*) from jumping to the wrong
conclusion.
Change the function to this:
def SaveEvents(self,events):
try:
plistlib.writePlist(events, self.path+'/Data/Events.plist')
return ''
except IOError as e:
return str(e)
# or if you prefer, your own custom error string
# "IOError: [Errno 13] Apache can't write Events.plist file"
I return a string in both cases so that you can, if you choose, use the
output of SaveEvents anywhere where a string is expected without worrying
about whether it returns None or a string:
content = Data.Dict.SaveEvents(Data.Plist.Events)
# content will be the empty string if no error, otherwise error message.
If you don't care about that, just delete the return '' line and the
function will fall back on returning None by default.
Either way, you can also use it like this:
content = Data.Dict.SaveEvents(Data.Plist.Events) or content
This will leave content unchanged if no error is returned, otherwise it
will replace the value. Note that content must have an initial value to
start with (presumably the empty string).
--
Steven
More information about the Python-list
mailing list