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