python - Catch exception and output them to django's messages system -
so noticed django has nice message framework. has 5 different levels (info, error, debug, warning, , success).
it nice propagate exception way views level, , report of these exceptions.
lib.py
def read_file(user, filename, **kwargs): try: open(...): return f.read() except exception, e: raise e utli.py
def wrapper_read_file(user, filename, **kwargs): try: if user.is_authenticated , user.belongs('admin'): lib.read_file(...) else: raise exception("unauthenticated user!!!") except exception, e: raise e views.py
def my_view(request): [..] 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 not exist.') elif isinstance(e, oserror): messages.add_message(request, message.error, 'you don't have sufficient permission open file.') return render(request, 'hello.html', {'hello_world': 'hello_world'} django knows how render messages , have facility that. display messages.
do think exception handling looks reasonable? alternative suggestions? pretty new python error exception handling.
you don't want catch every exception. may mask other errors, , things prevent ctrl-c working. instead, catch exceptions want handle.
try: # action may throw exception except ioerror, e: # 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: # catch oserrors messages.add_message(request, messages.error, "insufficient permissions") return render(request, 'hello.html', {}) update: added second except clause handle other exception type. note still insufficient, makes (big) assumption all oserrors permissions related.
Comments
Post a Comment