【问题标题】:impossible to catch asyncio.TimeoutError?无法捕获 asyncio.TimeoutError?
【发布时间】:2019-08-04 20:02:03
【问题描述】:

我正在使用 asyncio 来获取 url,有时它们会超时,尽我所能,我无法使用以下代码捕获 asyncio.TimeoutError!

async def fetch(url, session):
    """Fetch a url, using specified ClientSession."""
    async with session.get(url) as response:
        # print(f"fetching {url}")
        try:
            resp = await response.read()
        except asyncio.TimeoutError:
            return {"results": f"timeout error on {url}"}

        if response.status != 200:
            return {"error": f"server returned {response.status}"}

        return str(resp, 'utf-8').rstrip()

这是堆栈跟踪。我能做些什么来捕获这个异常并记录它而不是退出我的程序?

 resource: {…}  
 severity:  "ERROR"  
 textPayload:  "Traceback (most recent call last):
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 346, in run_http_function
    result = _function_handler.invoke_user_function(flask.request)
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 217, in invoke_user_function
    return call_user_function(request_or_event)
  File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 210, in call_user_function
    return self._user_function(request_or_event)
  File "/user_code/main.py", line 230, in gcf_update_all_featured_podcasts
    loop.run_until_complete(future)  # loop until done
  File "/opt/python3.7/lib/python3.7/asyncio/base_events.py", line 573, in run_until_complete
    return future.result()
  File "/user_code/main.py", line 201, in fetch_all
    _ = await asyncio.gather(*tasks)  # gather task responses
  File "/user_code/main.py", line 181, in fetch
    async with session.get(url) as response:
  File "/env/local/lib/python3.7/site-packages/aiohttp/client.py", line 1005, in __aenter__
    self._resp = await self._coro
  File "/env/local/lib/python3.7/site-packages/aiohttp/client.py", line 497, in _request
    await resp.start(conn)
  File "/env/local/lib/python3.7/site-packages/aiohttp/client_reqrep.py", line 857, in start
    self._continue = None
  File "/env/local/lib/python3.7/site-packages/aiohttp/helpers.py", line 585, in __exit__
    raise asyncio.TimeoutError from None
concurrent.futures._base.TimeoutError

【问题讨论】:

    标签: python exception python-asyncio


    【解决方案1】:

    在您的回溯中,您可以看到从您尝试向 url 发出请求的行引发了异常,但您的 try 块位于下一级。

    试试这样:

    async def fetch(url, session):
    """Fetch a url, using specified ClientSession."""
        try:
             async with session.get(url) as response:
             # print(f"fetching {url}")
                resp = await response.read()
                if response.status != 200:
                    return {"error": f"server returned {response.status}"}
    
                return str(resp, 'utf-8').rstrip()
    
        except asyncio.TimeoutError:
            return {"results": f"timeout error on {url}"}
    

    【讨论】:

      【解决方案2】:

      添加到 4xel 的解决方案

      在阅读之前检查状态是个好主意。

      async def fetch(url, session):
          """Fetch a url, using specified ClientSession."""
          resp = None
          try:
              async with session.get(url) as response:
                  if response.status != 200:
                      resp ={"error": f"server returned {response.status}"}
                  else:
                      resp = await response.read()
                      resp = str(resp, 'utf-8').rstrip()
          except asyncio.TimeoutError:
              resp = {"results": f"timeout error on {url}"}
          
          return resp
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-08
        • 2012-11-09
        • 2011-03-14
        • 2012-03-15
        • 2014-11-25
        • 2018-11-20
        • 1970-01-01
        相关资源
        最近更新 更多