Skip to content

Commit

Permalink
Include an example of middleware to handle error pages (#909)
Browse files Browse the repository at this point in the history
This serves both as an example of middleware, and as a useful hint as to
how to produce custom error pages (a common request).  Fixes #888.
  • Loading branch information
djmitche authored and asvetlov committed Jun 3, 2016
1 parent 0c912be commit 3177933
Showing 1 changed file with 29 additions and 0 deletions.
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

0 comments on commit 3177933

Please sign in to comment.