【问题标题】:How can I log/print a custom error message when response.raise_for_status() == 404?当 response.raise_for_status() == 404 时,如何记录/打印自定义错误消息?
【发布时间】:2023-02-22 00:21:51
【问题描述】:

我有一个实例,请求库没有捕获 404,而是将代码传递给另一个错误。为了捕获 404,我引入了 raise_for_status() 方法,它现在正确地停止了 HTTPError 处的代码。但是,它不再打印我的自定义错误消息,而是只提供堆栈跟踪。

这是代码

        try:
            response = requests.request(
                request_type, url, headers=headers, data=payload
            )
            response.raise_for_status()
        except requests.ConnectionError as ce:
            logger.info(
                f"""It appears you may need to check
                your internet connection - {ce}"""
            )
        except requests.exceptions.HTTPError as he:

            if response.raise_for_status() == 404:
                logger.info(
                    f"""We seem to be having an issue
                    with your request - {he.response}"""
                )
                logger.info(f"request - {he.request}")
        return response

这是收到 404 时我得到的完整堆栈跟踪:

Traceback (most recent call last):
  File "/home/user/projects/project_code/url_help/url_help.py", line 51, in connect_to_url
    response.raise_for_status()
  File "/home/user/projects/project_code/env/lib/python3.10/site-packages/requests/models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api-url.com/item/v3/companies/8951507/persons?page=1&pageSize=10

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/user/projects/project_code/main.py", line 99, in <module>
    main(args)
  File "/home/user/projects/project_code/main.py", line 50, in main
    ).get_employees_from_company_id(PAGE_SIZE, COMPANY_ID)
  File "/home/user/projects/project_code/employee_dict/employee_dict.py", line 109, in get_employees_from_company_id
    response = Url.connect_to_url(
  File "/home/user/projects/project_code/url_help/url_help.py", line 60, in connect_to_url
    if response.raise_for_status() == 404:
  File "/home/user/projects/project_code/env/lib/python3.10/site-packages/requests/models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api-url.com/item/v3/companies/8951507/persons?page=1&pageSize=10

有没有人对如何打印/记录消息有建议?在所有其他情况下,除了实际的错误编码之外,我还可以获得要记录的自定义消息。

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    raise_for_status 是一种在 http 请求失败时引发错误的方法,否则不返回任何内容。

    如果你想检查响应状态,你应该检查status_code,即,

    if response.status_code == 404:
        # do sth.
    

    【讨论】:

      【解决方案2】:

      raise_for_status 不是一个返回代码的函数,而是一个在状态代码不正常时会引发异常的函数。请改用 status_code 属性。例如:

          try:
              response = requests.request(request_type, url, headers=headers, data=payload)
      
              if response.status_code == 404:
                  logger.info(f"""We seem to be having an issue with your request - {he.response}""")
              else:
                  response.raise_for_status()
      
          except requests.ConnectionError as ce:
              ...
      

      如果您仍想在出现 404 时引发异常,只需删除 else:,并取消缩进以下对 response.raise_for_status() 的调用。

      【讨论】:

      • 感谢您的快速建议。不幸的是,这样做只会让我回到之前 404 被隐藏的位置,并且我得到一个空的 json 响应错误。由于这实际上是一个 404,我的代码应该到此为止。
      • 我已经编辑了答案,注意到如何“不”隐藏 404.. 只需删除 else。让我知道这是否有帮助
      【解决方案3】:

      您在 except 块中再次调用 raise_for_status 。这会重新引发异常,但不会被捕获。在 except 块内,您需要检查 status_code:

              try:
                  response = requests.request(
                      request_type, url, headers=headers, data=payload
                  )
                  response.raise_for_status()
              except requests.ConnectionError as ce:
                  logger.info(
                      f"""It appears you may need to check
                      your internet connection - {ce}"""
                  )
              except requests.exceptions.HTTPError as he:
      
                  if response.status_code == 404:
                      logger.info(
                          f"""We seem to be having an issue
                          with your request - {he.response}"""
                      )
                      logger.info(f"request - {he.request}")
              return response
      

      【讨论】:

        【解决方案4】:

        当您在 HTTPError 的 except 块内调用 response.raise_for_status() 时,它会引发另一个 HTTPError 实例,并且您尝试记录的自定义消息未被执行。

        要记录自定义消息,您可以访问包含错误消息的响应对象的文本属性,然后记录它。以下是修改 HTTPError 的 except 块的方法:

        except requests.exceptions.HTTPError as he:
            if response.status_code == 404:
                logger.info(
                    f"We seem to be having an issue with your request - {response.text}"
                )
                logger.info(f"Request - {response.request}")
            else:
                logger.info(f"HTTP error occurred: {he}")
        

        这将记录 response.text 属性中包含的错误消息以及自定义消息。如果响应状态代码不是 404,它将像以前一样记录原始 HTTPError 异常。

        请注意,您不需要在 except 块内再次调用 response.raise_for_status() 。 try 块中已经调用了 raise_for_status() 方法,如果没有抛出异常,则说明响应状态码不是错误,不需要再次检查。

        【讨论】:

          猜你喜欢
          • 2018-08-08
          • 2021-01-10
          • 1970-01-01
          • 2016-12-03
          • 2017-09-26
          • 2012-07-06
          • 2021-08-11
          • 1970-01-01
          • 2023-03-26
          相关资源
          最近更新 更多