Monday, November 3, 2014

Re: How to handle exceptions in RequestContext?

Hi Daniel,

On 11/03/2014 11:53 AM, Daniel Grace wrote:
> Say I have the following code:
>
> try:
> context_dict = {}
> context = RequestContext(request)
> ...
> except Exception as e:
> return render_to_response('error.html', context_dict, context)
>
> ...then how do I handle the exception without a context? Should I use
> the render function instead of render_to_response in the exception handler?

If your goal here is generic error handling for any unknown exception,
then why do you want to reuse the context? I would just create a new
simplified context with exactly what your `error.html` template
requires. It should be as stripped-down as possible (ideally avoiding
even RequestContext in favor of the simpler Context), otherwise it's not
a very useful generic error handler (if your first attempt to
instantiate a RequestContext failed for some unknown reason, why would
you expect a second attempt to succeed?)

Also, for generic error handling, you probably shouldn't be handling
that in your view code atll, but rather via something more reusable: a
view decorator, maybe, if you want it conditionally applied to some
views but not others, or a middleware with `process_exception`, or just
Django's built-in `500.html` template customizability.

If there's a particular exception specific to this view that you want to
handle (which is the only case where I'd recommend putting the error
handling directly in the view code), then you should be catching
something more specific than `Exception`, and wrapping much less code in
the `try` block - ideally only a single line of code, where you expect
the exception might be raised.

Carl

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5457D12A.8050207%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment