django-api-domains icon indicating copy to clipboard operation
django-api-domains copied to clipboard

[QUESTION] What's the best way to handle errors between apps?

Open frabraga opened this issue 6 years ago • 3 comments

Considering the example:

# user/internal.py
from .services import UserService

def get_user():
    try:
        UserService.get_user()
    except SomeIntegrationError:
        # Do something
# artists/interfaces.py
from user.apis import UserAPI

def get_user():
    return UserAPI.get_user()

What do you guys think it's the best way to handle this situation?

I'm thinking of just raise an exception on internal.py and ignore that we should return a Json or we could return a dict with an error key and check on interfaces if that key exists and then handle the error there. But I don't like either option.

frabraga avatar Mar 03 '20 21:03 frabraga

This is my immediate first thought:

  1. I would make UserAPI.get_user() raise a generic, but useful error:
def get_user():
    try:
        UserService.get_user()
    except SomeIntegrationError:
       raise UserError("A useful error message")
  1. If the artists domain needed to handle the errors for their own case, I would also make the interface capture the error and handle it how it wants:
from user.apis import UserAPI, UserError

def get_user():
    try:
        return UserAPI.get_user()
    except UserError:
        # Handle case specially for artists

As I said - they are my immediate thoughts, and might not prove useful.

I think returning an actual Exception if it is a software API is appropriate (I.e. - python code calling python code). If it is an HTTP API, then UserAPI.get_user should return an object with a defined error format that artist/interfaces can look out for:

from user.apis import UserAPI

def get_user():
    response = UserAPI.get_user()
    if response.get('errors'):
        # Handle errors in API response
    return response

phalt avatar Mar 03 '20 23:03 phalt

Thanks for your answer @phalt.

After thinking more about it, the Exception approach does make more sense to us and we'll go with it.

Thanks again!

frabraga avatar Mar 04 '20 13:03 frabraga

Thanks for your input @frabraga - you're helping to make this styleguide better!

Let me know if I can help any other way.

phalt avatar Mar 05 '20 00:03 phalt