Re: How to handle exceptions in RequestContext?

45 views
Skip to first unread message
Message has been deleted

Carl Meyer

unread,
Nov 3, 2014, 2:02:32 PM11/3/14
to django...@googlegroups.com
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

Daniel Grace

unread,
Nov 5, 2014, 10:44:28 AM11/5/14
to django...@googlegroups.com
I see where you are coming from Carl, thanks for the information.  Do you have a suitable example of where one might put error handling in the view code?

Carl Meyer

unread,
Nov 5, 2014, 12:28:41 PM11/5/14
to django...@googlegroups.com
Hi Daniel,
Usually I try to keep view code as short and simple as possible (because
it is the least reusable and hardest to test), pushing complexity into
more-reusable utility functions, form classes, etc instead. So it's
quite unusual for me to have an `except` statement directly in a view. I
checked my current project and here's the one case I found:

def oauth_callback(request, provider_key):
"""OAuth authorization callback for a specific provider."""
state = request.session.get('oauth_state', '')
provider = get_provider_or_404(None, provider_key, state=state)
auth_response = request.build_absolute_uri()
try:
user = provider.authorize(auth_response)
except UserConstraintError as exc:
messages.warning(
request,
"Cannot create or update user: "
"%s '%s' is invalid or already taken." % (exc.field, exc.value),
)
else:
if user is None:
messages.warning(request, "Unable to link account.")
else:
user.backend = settings.AUTHENTICATION_BACKENDS[0]
login(request, user)
return redirect('home')


A couple things to note here:

1. The `try:` block wraps only one statement. It's very rare that
there's a good case to have more than one statement in a `try` block
(unless it's a `try/finally` instead of `try/except`).

2. The `except` block catches one very specific exception class that I
expect `provider.authorize` might raise. The goal is to handle a
specific scenario; unexpected errors shouldn't pass silently.

3. As someone else in this thread already suggested, I'm handling the
error cases here by using `django.contrib.messages` to display an error
message.

Hope that helps,

Carl
Reply all
Reply to author
Forward
0 new messages