Reputation: 843
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.
Upvotes: 2
Views: 2952
Reputation: 35629
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.
try:
# action that may throw an exception
except IOError, e: # Will only catch IOErrors
if e.errno == errno.ENOENT:
messages.add_message(request, messages.ERROR, "File not found")
else:
raise e # Re-raise other IOErrors
except OSError, e: # Will only catch OSErrors
messages.add_message(request, messages.ERROR, "Insufficient permissions")
return render(request, 'hello.html', {})
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 OSErrors
are permissions related.
Upvotes: 3