When building web applications, you'll inevitably need to handle 404 errors - those pesky "page not found" messages when a user tries to access a URL that doesn't exist.
The Python aiohttp framework makes it easy to customize your 404 pages and handle these errors gracefully. Here's how:
Raising 404 Errors
First, you need to raise a 404 error in your aiohttp application when a route isn't found. You can do this with the
from aiohttp import web
routes = web.RouteTableDef()
@routes.get('/page')
async def handle(request):
raise web.HTTPNotFound()
This will raise a 404 error that aiohttp will catch.
Custom Error Handler
Next, setup a custom error handler that will render your 404 page:
async def error_handler(request, error):
if isinstance(error, web.HTTPNotFound):
return web.Response(text="Sorry, page not found", status=404)
else:
raise error
app = web.Application()
app.router.add_routes(routes)
app.add_routes([web.get('/{tail:.*}', error_handler)])
The key thing here is to check if the error is a 404, and handle that custom case accordingly.
Templating
For full customization, you'll want to render a template instead of just returning text. Make sure your template engine is configured with aiohttp, and then render the template:
return web.Response(
text=self.template.render('404.html'),
status=404
)
Final Touches
Add some nice styling to the page, perhaps some helpful links, and you've got yourself a polished 404 page that doesn't look like an ugly default error.
Handling 404s gracefully is essential for a good user experience. With aiohttp, it's straightforward to raise the errors and handle them properly. Add custom templates and styling, and those pesky 404s won't be so bad after all!