httpnotfound aiohttp

Feb 22, 2024 ยท 2 min read

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 aiohttp.web.HTTPNotFound exception:

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!

Browse by tags:

Browse by language:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: