So I noticed that Django has a nice message framework. It has 5 different levels (info, error, debug, warning, and success).
It would be really nice to propagate the exception all the way up to the views level, and report some of these exceptions.
lib.py
def read_file(user, filename, **kwargs):
try:
with open(...):
return f.read()
except Exception, e:
raise e
utli.py
def wrapper_read_file(user, filename, **kwargs):
try:
if user.is_authenticated and user.belongs('admin'):
lib.read_file(...)
else:
raise Exception("Unauthenticated user!!!")
except Exception, e:
raise e
views.py
def my_view(request):
[..] do something here
try:
result = wrapper_read_file(...)
return render(request, 'hello.html', {'result': result})
except Exception, e:
if isinstance(e, IOError):
if e.errno==errno.ENOENT:
messages.add_message(request, message.ERROR, 'File does not exist.')
elif isinstance(e, OSError):
messages.add_message(request, message.ERROR, 'You don't have sufficient permission to open the file.')
return render(request, 'hello.html', {'hello_world': 'hello_world'}
Django knows how to render the messages and I have the facility to do that. So it will display messages.
Do you think my exception handling looks reasonable? Any alternative suggestions? I am pretty new to Python error exception handling.
You probably don’t want to catch every exception. This may mask other errors, and will do things like prevent Ctrl-C from working. Instead, catch only the exceptions you want to handle.
Update: added a second except clause to handle other another exception type. Note that this is still probably insufficient, as this makes the (big) assumption that all
OSErrorsare permissions related.