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
1 change: 1 addition & 0 deletions CHANGES/3483.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Internal Server Errors in plain text if the browser does not support HTML.
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
38 changes: 25 additions & 13 deletions aiohttp/web_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,22 +524,34 @@ 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', ''):
if self.debug:
with suppress(Exception):
tb = traceback.format_exc()
tb = html_escape(tb)
msg = '<h2>Traceback:</h2>\n<pre>{}</pre>'.format(tb)
else:
msg = 'Server got itself in trouble'
msg = (
"<html><head>"
"<title>500 Internal Server Error</title>"
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
"</head><body>\n<h1>500 Internal Server Error</h1>"
"<br>\n{msg}\n</body></html>\n"
).format(msg=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')
if self.debug:
with suppress(Exception):
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
msg = traceback.format_exc()
else:
msg = 'Server got itself in trouble'
msg = '500 Internal Server Error\n\n' + msg
resp = Response(status=status, text=msg,
content_type='text/plain')
else:
resp = Response(status=status, text=message,
content_type='text/html')
content_type='text/plain')
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved

resp.force_close()

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
60 changes: 57 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,62 @@ 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 (most recent call last):\n' 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 == (
'<html><head><title>500 Internal Server Error</title></head><body>\n'
'<h1>500 Internal Server Error</h1><br>\n'
'Server got itself in trouble\n'
'</body></html>\n'
)

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(
'<html><head><title>500 Internal Server Error</title></head><body>\n'
'<h1>500 Internal Server Error</h1><br>\n'
'<h2>Traceback:</h2>\n'
'<pre>Traceback (most recent call last):\n'
)

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