The best way to suppress exceptions that arise when third-party services are unavailable?

I wrote a Django application that interacts with a third-party API (Disqus, although this detail is not important) through the Python shell. When a service is unavailable, the Python shell throws an exception.

The best way for an application to handle such exceptions is to suppress them so that the rest of the page content can be displayed to the user. The following works great.

try:
    somemodule.method_that_may_raise_exception(args)
except somemodule.APIError:
    pass

Some views contain several such calls. Is wrapping every call in try / except the best way to suppress possible exceptions?

+3
source share
2 answers

API - . , , .

. Facebook, publish.py " ". , . :.

# publish.py
def authorise_application(user):
    # API call "User joined app."

def post_anwser(anwser):
    # API call "User posted anwser to quiz".

:

# views.py
def post_anwser(request):
    ...
    if form.is_valid():
        form.save()
        publish.post_anwser(form.instance)

, :

# publish.py
def ignore_api_error(fun):
    def res(*args, **kwargs):
        try:
            return fun(*args, **kwargs):
        except someservice.ApiError:
            return None
    return res

@ignore_api_error
def authorised_application(user):
    # API call "User joined app."

@ignore_api_error
def posted_anwser(user, anwser):
    # API call "User posted anwser to quiz".

, , :

# publish.py
def some_function(user, message):
    pass

# views.py
def my_view():
    ...
    publish.ignore_api_error(publish.some_function)(user, message)
    ...
+2

. try/except ?

API . :

def make_api_call(*args, **kwargs):
    try:
        return somemodule.method_that_may_raise_exception(*args, **kwargs)
    except somemodule.APIError:
        log.warn("....")           

try/except . , , , , .

@Yorirou . .

+1

Source: https://habr.com/ru/post/1764276/


All Articles