Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
tornado: Report errors as JSON instead of rendering portico pages.
Aman Agrawald74973f03dd3
diff --git a/zerver/tests/test_tornado.py b/zerver/tests/test_tornado.pyindex 227c7067ff6..990b726c656 100644--- a/zerver/tests/test_tornado.py+++ b/zerver/tests/test_tornado.py@@ -196,3 +196,34 @@ class EventsTestCase(TornadoWebTestCase):self.assert_length(queries, 1)self.assertIn("django_session", queries[0].sql)+++class ErrorHandlingTestCase(TornadoWebTestCase):+ async def test_url_not_found(self) -> None:+ # nginx merges the duplicate slashes when matching its+ # `location` block, but proxies the original path.+ async with self.with_tornado():+ response = await self.fetch_async(+ "GET", "//api/v1/events", subdomain="zulip", raise_error=False+ )+ self.assertEqual(response.code, 404)+ self.assertEqual(orjson.loads(response.body), {"result": "error", "msg": "Not found"})++ async def test_uncaught_exception(self) -> None:+ async with self.with_tornado():+ await sync_to_async(lambda: self.login_user(self.example_user("hamlet")))()+ with (+ mock.patch(+ "zerver.tornado.views.fetch_events", side_effect=Exception("test error")+ ),+ self.assertLogs("django.request", level="ERROR") as error_log,+ ):+ response = await self.fetch_async(+ "GET", "/json/events?dont_block=true", subdomain="zulip", raise_error=False+ )+ self.assertEqual(response.code, 500)+ self.assertEqual(+ orjson.loads(response.body),+ {"result": "error", "msg": "Internal server error"},+ )+ self.assertIn("Internal Server Error: /json/events", error_log.output[0])diff --git a/zerver/tornado/views.py b/zerver/tornado/views.pyindex 82a12e6d0c3..449b5e16b46 100644--- a/zerver/tornado/views.py+++ b/zerver/tornado/views.py@@ -13,7 +13,7 @@ from zerver.decorator import internal_api_view, process_clientfrom zerver.lib.exceptions import JsonableErrorfrom zerver.lib.queue import get_queue_clientfrom zerver.lib.request import RequestNotes-from zerver.lib.response import AsynchronousResponse, json_success+from zerver.lib.response import AsynchronousResponse, json_response, json_successfrom zerver.lib.sessions import narrow_request_userfrom zerver.lib.typed_endpoint import ApiParamConfig, DocumentationStatus, typed_endpointfrom zerver.models import UserProfile@@ -38,6 +38,15 @@ def in_tornado_thread(f: Callable[P, T]) -> Callable[P, T]:return async_to_sync(wrapped)+# Registered as handler404/handler500 by zproject/tornado_urls.py.+def json_not_found(request: HttpRequest, exception: Exception) -> HttpResponse:+ return json_response(res_type="error", msg=_("Not found"), status=404)+++def json_internal_server_error(request: HttpRequest) -> HttpResponse:+ return json_response(res_type="error", msg=_("Internal server error"), status=500)++@internal_api_view(True)@typed_endpointdef notify(request: HttpRequest, *, data: Json[dict[str, Any]]) -> HttpResponse:diff --git a/zproject/tornado_urls.py b/zproject/tornado_urls.pyindex db4c1498949..1a2120e4d88 100644--- a/zproject/tornado_urls.py+++ b/zproject/tornado_urls.py@@ -23,6 +23,11 @@ api_and_json_patterns = [),]+# Tornado serves only API endpoints, and this configuration lacks the+# URL names that Zulip's HTML error pages reverse.+handler404 = "zerver.tornado.views.json_not_found"+handler500 = "zerver.tornado.views.json_internal_server_error"+urlpatterns = [path("api/v1/", include(api_and_json_patterns)),path("json/", include(api_and_json_patterns)),