"""
This module contains the basic middlewares to be used (passed to
:func:`ourobori.apps.http.run_service`) in the ``service.py`` of your own
service based on ourobori.
"""
import asyncio
import functools
from aiohttp import web
from aiohttp.web import Application
from aiohttp.web_request import Request
[docs]async def error_middleware(app: Application, handler: functools.partial):
"""
Middleware to handle the errors occuring in the service.
The handler defined inside handles different exception-cases as default.
Additional error-handling has to be defined inside the service rules
in ``Rules.handle_exceptions``.
The exceptions defined there have to inherit from
:class:`ourobori.services.errors.BaseException` to be handled
automatically by this error_middleware.
Parameters:
app: The application serving the apis
handler: The handler for the requested api
"""
async def middleware_handler(request: Request):
try:
response = await handler(request)
return response
except web.HTTPNotFound as err:
response = web.json_response(status=404)
return response
except web.HTTPException as err:
response = web.Response(body=str(err), status=err.status)
request.app.logger.exception('Oops ...')
return response
except request.app.rules.handle_exceptions as err:
response = web.json_response(status=err.status, data=err.data)
request.app.logger.exception('Oops ...')
return response
except Exception as err:
response = web.json_response(status=500)
request.app.logger.exception('Oops ...')
return response
return middleware_handler
__all__ = ['error_middleware']