欢迎访问宙启技术站
智能推送

如何处理Python中aiohttp模块发起的异步请求引发的ClientResponseError异常

发布时间:2024-01-12 14:44:07

aiohttp是Python中一个用于处理异步HTTP请求的模块。当使用aiohttp发起异步请求时,有可能会出现ClientResponseError异常。ClientResponseError异常通常是由于请求返回的响应状态码不在200-299的范围内引起的。

处理ClientResponseError异常的方法有以下几种:

1. 使用try-except语句来捕获异常并处理。在try块中发起异步请求,然后在except块中处理异常。可以根据异常的类型来进行不同的处理,例如打印错误信息、记录日志或者进行重试等。

下面是一个使用try-except语句处理ClientResponseError异常的示例:

import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        try:
            response.raise_for_status()  # 检查响应状态码
            return await response.text()
        except aiohttp.ClientResponseError as e:
            print(f"Request failed with status code {e.status}")
            # 其他处理代码

async def main():
    async with aiohttp.ClientSession() as session:
        url = 'http://example.com'
        try:
            html = await fetch(session, url)
            print(html)
        except aiohttp.ClientError as e:
            print(f"Request failed: {e}")

# 运行入口
if __name__ == '__main__':
    asyncio.run(main())

2. 使用aiohttp.ClientResponseError的子类来捕获特定类型的异常。aiohttp提供了一些不同的异常类,可以用于捕获特定的错误。可以根据异常的类型来进行不同的处理,例如重试、记录日志等。

以下是一个使用特定异常类捕获ClientResponseError异常的示例:

import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        try:
            response.raise_for_status()  # 检查响应状态码
            return await response.text()
        except aiohttp.ClientResponseError as e:
            if isinstance(e, aiohttp.ClientResponseError) and e.status == 404:
                # 特定错误处理
                print("Page not found")
            else:
                # 其他错误处理
                print(f"Request failed with status code {e.status}")

async def main():
    async with aiohttp.ClientSession() as session:
        url = 'http://example.com'
        try:
            html = await fetch(session, url)
            print(html)
        except aiohttp.ClientError as e:
            print(f"Request failed: {e}")

# 运行入口
if __name__ == '__main__':
    asyncio.run(main())

这是处理ClientResponseError异常的两种常见方法。使用这些方法,您可以根据特定的需求来处理这些异常,并执行相应的操作,例如记录日志、重试、显示错误信息等。记得根据具体情况选择适合自己的处理方法。