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 :)