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

Include an example of middleware to handle error pages #909

Merged
merged 1 commit into from
Jun 3, 2016
Merged
Changes from all 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
29 changes: 29 additions & 0 deletions docs/web.rst
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,35 @@ post-processing like handling *CORS* and so on.
Middlewares accept route exceptions (:exc:`HTTPNotFound` and
:exc:`HTTPMethodNotAllowed`).

Example
.......

A common use of middlewares is to implement custom error pages. The following
example will render 404 errors using a JSON response, as might be appropriate
a JSON REST service:

import json
from aiohttp import web

def json_error(message):
return web.Response(
body=json.dumps({'error': message}).encode('utf-8'),
content_type='application/json')

async def error_middleware(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
if response.status == 404:
return json_error(response.message)
return response
except web.HTTPException as ex:
if ex.status == 404:
return json_error(ex.reason)
raise
return middleware_handler

app = web.Application(middlewares=[error_middleware])

.. _aiohttp-web-signals:

Expand Down