From d9c538c08fbcfa71bc439f3f1b7a51123a6a6ed2 Mon Sep 17 00:00:00 2001 From: "Dustin J. Mitchell" Date: Fri, 3 Jun 2016 19:46:39 +0000 Subject: [PATCH] Include an example of middleware to handle error pages 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. --- docs/web.rst | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/web.rst b/docs/web.rst index b3aeb5c4fca..ffbe45d46c2 100644 --- a/docs/web.rst +++ b/docs/web.rst @@ -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: