Hi Daniel,

On 11/05/2014 08:44 AM, Daniel Grace wrote:
> 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?

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

-- 
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+unsubscr...@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/545A5E2F.5050005%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.

Reply via email to