best practice for error handling in aiohttp

1,173 views
Skip to first unread message

h h

unread,
Jun 15, 2017, 7:25:33 AM6/15/17
to aio-libs
Hi, Community!

I was impressed by mypy and added it to my project, but I've faced problem how to handle errors

So I've written 3 examples to discuss, could you guide me?

first, through exceptions
class MyException(Exception):
    pass


async def something(param: str) -> Dict[int, List[str]]:
    if param == "fail":
        raise MyException("fail")
    return {
        1: [param],
        2: [param, param],
        3: [param, param, param]
    }


async def hello(request: web.Request):
    param = request.rel_url.query['param']
    try:
        answer = await something(param)
    except MyException as e:
        return web.json_response({
            'status': False,
            'msg': str(e)
        })
    return web.json_response({
        'status': True,
        'data': answer
    })

second, when function returns either error or result
class Error:
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg


async def something(param: str) -> Union[Error, Dict[int, List[str]]]:
    if param == "fail":
        return Error("fail")
    return {
        1: [param],
        2: [param, param],
        3: [param, param, param]
    }


async def hello(request: web.Request):
    param = request.rel_url.query['param']
    answer = await something(param)
    if isinstance(answer, Error):
        return web.json_response({
            'status': False,
            'msg': answer
        })
    return web.json_response({
        'status': True,
        'data': answer
    })

third, like in GO language
class Error:
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg


async def something(param: str) -> Tuple[Dict[int, List[str]], Optional[Error]]:
    if param == "fail":
        return {}, Error("fail")
    return {
        1: [param],
        2: [param, param],
        3: [param, param, param]
    }, None


async def hello(request: web.Request):
    param = request.rel_url.query['param']
    answer, error = await something(param)
    if error is not None:
        return web.json_response({
            'status': False,
            'msg': error
        })
    return web.json_response({
        'status': True,
        'data': answer
    })

maybe something else?

Thanks for wonderful framework :)

Alexander Shorin

unread,
Jun 15, 2017, 7:34:22 AM6/15/17
to h h, aio-libs
Hi,

I prefer error middleware where I catch all the exceptions and do
something with them. Like send them to Sentry or convert into HTTP
error response with json body.

For non-hello-world app you unlikely would like to have error
processing in every route.

So go with middleware based first example, but certainly don't with third.


--
,,,^..^,,,
> --
> You received this message because you are subscribed to the Google Groups
> "aio-libs" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to aio-libs+u...@googlegroups.com.
> To post to this group, send email to aio-...@googlegroups.com.
> Visit this group at https://groups.google.com/group/aio-libs.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/aio-libs/4f92024b-32df-4fc0-b07c-ded65d72ab5c%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

h h

unread,
Jun 15, 2017, 8:18:25 AM6/15/17
to aio-libs, here...@gmail.com
Is that exceptions are slower than just return? collect traceback, you know...

четверг, 15 июня 2017 г., 14:34:22 UTC+3 пользователь Alexander Shorin написал:

Alexander Shorin

unread,
Jun 15, 2017, 8:33:50 AM6/15/17
to h h, aio-libs
On Thu, Jun 15, 2017 at 3:18 PM, h h <here...@gmail.com> wrote:
> Is that exceptions are slower than just return? collect traceback, you
> know...

If exception happens performance is the last you should care about
since you have a bug to fix (:
By returning exception you loose information where the error actually happened.

--
,,,^..^,,,
Reply all
Reply to author
Forward
0 new messages