Skip to content

Commit

Permalink
Return JSON error responses for unknown routes/methods. (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
clokep authored Nov 29, 2023
1 parent db49ec6 commit 2151f88
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/matrix_content_scanner/httpserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,31 @@ async def simple_cors_middleware(
return response


@web.middleware
async def json_errors_middleware(
request: web.Request,
handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
"""A simple aiohttp middleware that converts 404/405 errors into Matrix JSON error.
Args:
request: The request to handle.
handler: The handler for this request.
Returns:
The original response OR a JSON error response.
"""
# Run the request's handler and append CORS headers to it.
try:
return await handler(request)
except (web.HTTPNotFound, web.HTTPMethodNotAllowed) as ex:
# Return the proper JSON response.
return web.json_response(
{"errcode": "M_UNRECOGNIZED", "error": "Unrecognized request"},
status=ex.status,
)


class HTTPServer:
def __init__(self, mcs: "MatrixContentScanner"):
self._mcs = mcs
Expand Down Expand Up @@ -117,6 +142,8 @@ def _build_app(self) -> web.Application:
web.normalize_path_middleware(),
# Handler CORS.
simple_cors_middleware,
# Convert unknown routes/methods into JSON errors.
json_errors_middleware,
],
)
root.add_subapp("/_matrix/media_proxy/unstable", app)
Expand Down

0 comments on commit 2151f88

Please sign in to comment.