Search code examples
pythonwebserveraiohttp

Errorhandler aiohttp webserver?


How can I create http error router in aiohttp web server?

   from aiohttp import web
   routes = list()
   routes.append(web.route('POST', '/reg', handler))

How can I create for example:

routes.append(web.error_handler(404, handler404)


Solution

  • Common way to create custom error pages in aiohttp is to use middleware:

    from aiohttp import web
    
    
    @web.middleware
    async def error_middleware(request, handler):
        try:
            response = await handler(request)
            # this is needed to handle ``return web.HTTPNotFound()`` case
            if response.status == 404:
                return web.Response(text='First custom 404 message', status=404)
            return response
        except web.HTTPException as ex:
            # this is needed to handle ``raise web.HTTPNotFound()`` case
            if ex.status == 404:
                return web.Response(text='Second custom 404 message', status=404)
            raise
        # this is needed to handle non-HTTPException
        except Exception:
            return web.Response(text='Oops, something went wrong', status=500)
    
    
    app = web.Application(middlewares=[error_middleware])
    

    One more example is here