在python中使用except捕獲任何類型的異常


1 try:
2     正常的操作
3    ......................
4 except:
5     發生異常,執行這塊代碼
6    ......................
7 else:
8     如果沒有異常執行這塊代碼

使用except二不帶任何的異常類型,可以捕獲程序代碼中的所有異常信息,這種方式捕獲的異常不區分類型,雖然官方不推薦使用,但是我覺得在發送http請求中使用的比較廣泛,可以有效的減少程序因遇到異常而退出。

  from loguru import logger


def _handle_request_error(self, method, request_path, params):

        if method == c.GET:
            request_path = request_path + utils.parse_params_to_str(params)
        # url
        url = c.API_URL + request_path

        timestamp = utils.get_timestamp()

        # sign & header
        if self.use_server_time:
            timestamp = self._get_timestamp()

        body = json.dumps(params) if method == c.POST else ""

        sign = utils.sign(utils.pre_hash(timestamp, method, request_path, str(body)), self.API_SECRET_KEY)
        header = utils.get_header(self.API_KEY, sign, timestamp, self.PASSPHRASE, self.flag)

        # send request
        response = None

        if method == c.GET:
            response = requests.get(url, headers=header)
        elif method == c.POST:
            response = requests.post(url, data=body, headers=header)

        return response

    def _request(self, method, request_path, params):
        sleep_times = 1
        tmp_method = method
        tmp_request_path = request_path
        tmp_params = params

        try:
            if method == c.GET:
                request_path = request_path + utils.parse_params_to_str(params)
            # url
            url = c.API_URL + request_path

            timestamp = utils.get_timestamp()

            # sign & header
            if self.use_server_time:
                timestamp = self._get_timestamp()

            body = json.dumps(params) if method == c.POST else ""

            sign = utils.sign(utils.pre_hash(timestamp, method, request_path, str(body)), self.API_SECRET_KEY)
            header = utils.get_header(self.API_KEY, sign, timestamp, self.PASSPHRASE, self.flag)

            # send request
            response = None

            if method == c.GET:
                response = requests.get(url, headers=header)
            elif method == c.POST:
                response = requests.post(url, data=body, headers=header)
        except
            while not str(response.status_code).startswith('2'):
                time.sleep(2)
                response = self._handle_request_error(tmp_method, tmp_request_path, tmp_params)
                append_write_file(str(response))
                datetime.datetime.now()
                append_write_file(str(datetime.datetime.now()) + " 請求的Url=" + str(url))
                append_write_file(str(datetime.datetime.now()) + " 請求的body=" + str(body))
                append_write_file(str(datetime.datetime.now()) + " 進入請求循環不斷的進行相關的請求")
                sleep_times = sleep_times + random.randint(0, 9)
                print(str(response))
            return response.json()
        else:
            print("請求發送正常")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM