Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions channels/generic/http.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import logging
import traceback

from channels.consumer import AsyncConsumer

from ..db import aclose_old_connections
from ..exceptions import StopConsumer

logger = logging.getLogger("channels.consumer")
logger.setLevel(logging.DEBUG)


class AsyncHttpConsumer(AsyncConsumer):
"""
Expand Down Expand Up @@ -77,9 +83,14 @@ async def http_request(self, message):
"""
if "body" in message:
self.body.append(message["body"])

if not message.get("more_body"):
try:
await self.handle(b"".join(self.body))
except Exception:
logger.error(f"Error in handle(): {traceback.format_exc()}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about using logger.exception() ?

await self.send_response(500, b"Internal Server Error")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this is the essence of the proposal.

raise
finally:
await self.disconnect()
raise StopConsumer()
Expand Down
39 changes: 39 additions & 0 deletions tests/test_generic_http.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import json
import time
from unittest.mock import patch

import pytest

Expand Down Expand Up @@ -142,3 +143,41 @@ def send_awaitable_callable(*args, **kwargs):
assert response["body"] == b"42"
assert response["status"] == 200
assert response["headers"] == [(b"Content-Type", b"text/plain")]


@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_error_logging():
"""Regression test for error logging."""

class TestConsumer(AsyncHttpConsumer):
async def handle(self, body):
raise AssertionError("Error correctly raised")

communicator = HttpCommunicator(TestConsumer(), "GET", "/")
with patch("channels.generic.http.logger.error") as mock_logger_error:
try:
await communicator.get_response(timeout=0.05)
except AssertionError:
pass
args, _ = mock_logger_error.call_args
assert "Error in handle()" in args[0]
assert "AssertionError: Error correctly raised" in args[0]


@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_error_handling_and_send_response():
"""Regression test to check error handling."""

class TestConsumer(AsyncHttpConsumer):
async def handle(self, body):
raise AssertionError("Error correctly raised")

communicator = HttpCommunicator(TestConsumer(), "GET", "/")
with patch.object(AsyncHttpConsumer, "send_response") as mock_send_response:
try:
await communicator.get_response(timeout=0.05)
except AssertionError:
pass
mock_send_response.assert_called_once_with(500, b"Internal Server Error")
Loading