Django - Catch Exception
Looking at this code: try: ... # do something except: raise Exception('XYZ has gone wrong...') Even with DEBUG=True, I don't want this raise Exception to give that yellow p
Solution 1:
You have three options here.
- Provide a 404 handler or 500 handler
- Catch the exception elsewhere in your code and do appropriate redirection
- Provide custom middleware with the
process_exception
implemented
Middleware Example:
classMyExceptionMiddleware(object):
defprocess_exception(self, request, exception):
ifnotisinstance(exception, SomeExceptionType):
returnNonereturn HttpResponse('some message')
Solution 2:
You can raise a 404 error or simply redirect user onto your custom error page with error message
from django.http import Http404
#...defyour_view(request)
#...try:
#... do somethingexcept:
raise Http404
#orreturn redirect('your-custom-error-view-name', error='error messsage')
Solution 3:
Another suggestion could be to use Django messaging framework to display flash messages, instead of an error page.
from django.contrib import messages
#...defanother_view(request):
#...
context = {'foo': 'bar'}
try:
#... some stuff hereexcept SomeException as e:
messages.add_message(request, messages.ERROR, e)
return render(request, 'appname/another_view.html', context)
And then in the view as in Django documentation:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
Solution 4:
If you want to get proper traceback and message as well. Then I will suggest using a custom middleware and add it to the settings.py middleware section at the end.
The following code will process the exception only in production. You may remove the DEBUG condition if you wish.
from django.http import HttpResponse
from django.conf import settings
import traceback
classErrorHandlerMiddleware:
def__init__(self, get_response):
self.get_response = get_response
def__call__(self, request):
response = self.get_response(request)
return response
defprocess_exception(self, request, exception):
ifnot settings.DEBUG:
if exception:
message = "{url}\n{error}\n{tb}".format(
url=request.build_absolute_uri(),
error=repr(exception),
tb=traceback.format_exc()
)
# Do whatever with the message nowreturn HttpResponse("Error processing the request.", status=500)
Post a Comment for "Django - Catch Exception"