Skip to content

Instantly share code, notes, and snippets.

@amitripshtos
Created July 18, 2017 08:56
Show Gist options
  • Save amitripshtos/854da3f4217e3441e8fceea85b0cbd91 to your computer and use it in GitHub Desktop.
Save amitripshtos/854da3f4217e3441e8fceea85b0cbd91 to your computer and use it in GitHub Desktop.
Exception handling middleware for aiohttp (python 3.5)
def json_error(status_code: int, exception: Exception) -> web.Response:
"""
Returns a Response from an exception.
Used for error middleware.
:param status_code:
:param exception:
:return:
"""
return web.Response(
status=status_code,
body=json.dumps({
'error': exception.__class__.__name__,
'detail': str(exception)
}).encode('utf-8'),
content_type='application/json')
async def error_middleware(app: web.Application, handler):
"""
This middleware handles with exceptions received from views or previous middleware.
:param app:
:param handler:
:return:
"""
async def middleware_handler(request):
try:
response = await handler(request)
if response.status == 404:
return json_error(response.status, Exception(response.message))
return response
except web.HTTPException as ex:
if ex.status == 404:
return json_error(ex.status, ex)
raise
except Exception as e:
logger.warning('Request {} has failed with exception: {}'.format(request, repr(e)))
return json_error(500, e)
return middleware_handler
app = web.Application(middlewares=[error_middleware])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment