在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("请求发送正常")