Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

plain text http responses to errors #3483

Merged
merged 12 commits into from
Jan 7, 2019
2 changes: 1 addition & 1 deletion aiohttp/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ async def _make_runner(self,
debug: bool=True,
**kwargs: Any) -> ServerRunner:
srv = Server(
self._handler, loop=self._loop, debug=True, **kwargs)
self._handler, loop=self._loop, debug=debug, **kwargs)
return ServerRunner(srv, debug=debug, **kwargs)


Expand Down
41 changes: 29 additions & 12 deletions aiohttp/web_protocol.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import asyncio.streams
import textwrap
import traceback
import warnings
from collections import deque
Expand Down Expand Up @@ -524,19 +525,35 @@ def handle_error(self,
self.log_exception("Error handling request", exc_info=exc)

if status == 500:
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
msg = "<h1>500 Internal Server Error</h1>"
if self.debug:
with suppress(Exception):
tb = traceback.format_exc()
tb = html_escape(tb)
msg += '<br><h2>Traceback:</h2>\n<pre>'
msg += tb
msg += '</pre>'
if 'text/html' in request.headers.get('Accept', ''):
msg = "<h1>500 Internal Server Error</h1>"
if self.debug:
with suppress(Exception):
tb = traceback.format_exc()
tb = html_escape(tb)
msg += '<br><h2>Traceback:</h2>\n<pre>'
msg += tb
msg += '</pre>'
else:
msg += "Server got itself in trouble"
msg = (
"<html><head>"
"<title>500 Internal Server Error</title>"
"</head><body>{msg}</body></html>"
).format(msg)
resp = Response(status=status, text=msg,
content_type='text/html')
else:
msg += "Server got itself in trouble"
msg = ("<html><head><title>500 Internal Server Error</title>"
"</head><body>" + msg + "</body></html>")
resp = Response(status=status, text=msg, content_type='text/html')
msg = '500 Internal Server Error'
if self.debug:
with suppress(Exception):
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
msg += '\n\nTraceback:\n'
tb = traceback.format_exc()
msg += textwrap.indent(tb, ' ')
else:
msg += '\n\nServer got itself in trouble'
resp = Response(status=status, text=msg,
content_type='text/plain')
else:
resp = Response(status=status, text=message,
content_type='text/html')
Expand Down
2 changes: 1 addition & 1 deletion tests/test_web_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ async def test_handle_error__utf(
await asyncio.sleep(0)

assert b'HTTP/1.0 500 Internal Server Error' in buf
assert b'Content-Type: text/html; charset=utf-8' in buf
assert b'Content-Type: text/plain; charset=utf-8' in buf
pattern = escape("RuntimeError: что-то пошло не так")
assert pattern.encode('utf-8') in buf
assert not srv._keepalive
Expand Down
52 changes: 49 additions & 3 deletions tests/test_web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@ async def handler(request):
raise exc

logger = mock.Mock()
server = await aiohttp_raw_server(handler, logger=logger)
server = await aiohttp_raw_server(handler, logger=logger, debug=False)
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
cli = await aiohttp_client(server)
resp = await cli.get('/path/to')
assert resp.status == 500
assert resp.headers['Content-Type'].startswith('text/plain')

txt = await resp.text()
assert "<h1>500 Internal Server Error</h1>" in txt
assert txt.startswith("500 Internal Server Error")
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
assert "Traceback:" not in txt

logger.exception.assert_called_with(
"Error handling request",
Expand Down Expand Up @@ -102,10 +104,54 @@ async def handler(request):
cli = await aiohttp_client(server)
resp = await cli.get('/path/to')
assert resp.status == 500
assert resp.headers['Content-Type'].startswith('text/plain')

txt = await resp.text()
assert "<h2>Traceback:</h2>" in txt
assert "Traceback:" in txt

logger.exception.assert_called_with(
"Error handling request",
exc_info=exc)


async def test_raw_server_html_exception(aiohttp_raw_server, aiohttp_client):
exc = RuntimeError("custom runtime error")

async def handler(request):
raise exc

logger = mock.Mock()
server = await aiohttp_raw_server(handler, logger=logger, debug=False)
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
cli = await aiohttp_client(server)
resp = await cli.get('/path/to', headers={'Accept': 'text/html'})
assert resp.status == 500
assert resp.headers['Content-Type'].startswith('text/html')

txt = await resp.text()
assert txt.startswith("<h1>500 Internal Server Error</h1>")
assert "Traceback" not in txt

logger.exception.assert_called_with(
"Error handling request", exc_info=exc)


async def test_raw_server_html_exception_debug(aiohttp_raw_server,
aiohttp_client):
exc = RuntimeError("custom runtime error")

async def handler(request):
raise exc

logger = mock.Mock()
server = await aiohttp_raw_server(handler, logger=logger, debug=True)
cli = await aiohttp_client(server)
resp = await cli.get('/path/to', headers={'Accept': 'text/html'})
assert resp.status == 500
assert resp.headers['Content-Type'].startswith('text/html')

txt = await resp.text()
assert txt.startswith("<h1>500 Internal Server Error</h1>")
assert "<h2>Traceback:</h2>" in txt

logger.exception.assert_called_with(
"Error handling request", exc_info=exc)