From d35d7ffbe24c641dc62b9680cf99f1ce719643d7 Mon Sep 17 00:00:00 2001 From: Ankush Menat Date: Tue, 28 Jun 2022 18:01:12 +0530 Subject: [PATCH] fix: remove bare exception catching A bare except catches lots of things (like generator iteration end) and should never be used. --- .github/helper/flake8.conf | 1 - frappe/build.py | 2 +- frappe/commands/scheduler.py | 2 +- frappe/core/doctype/doctype/test_doctype.py | 2 +- frappe/core/doctype/user/user.py | 2 +- frappe/database/database.py | 2 +- .../doctype/system_console/system_console.py | 2 +- frappe/email/__init__.py | 32 ++++++++----------- frappe/email/doctype/newsletter/newsletter.py | 2 +- .../doctype/notification/notification.py | 2 +- frappe/email/receive.py | 6 ++-- frappe/installer.py | 2 +- .../razorpay_settings/razorpay_settings.py | 16 ++++------ frappe/model/mapper.py | 2 +- .../generate_theme_files_in_public_folder.py | 2 +- frappe/twofactor.py | 2 +- frappe/utils/background_jobs.py | 2 +- frappe/utils/data.py | 4 +-- frappe/utils/pdf.py | 2 +- frappe/utils/scheduler.py | 2 +- 20 files changed, 40 insertions(+), 49 deletions(-) diff --git a/.github/helper/flake8.conf b/.github/helper/flake8.conf index a7f1f70da3..20d4b912ca 100644 --- a/.github/helper/flake8.conf +++ b/.github/helper/flake8.conf @@ -69,7 +69,6 @@ ignore = F841, E713, E712, - E722, max-line-length = 200 diff --git a/frappe/build.py b/frappe/build.py index 5923bd05ec..a7fdb47677 100644 --- a/frappe/build.py +++ b/frappe/build.py @@ -205,7 +205,7 @@ def symlink(target, link_name, overwrite=False): os.replace(temp_link_name, link_name) except AttributeError: os.renames(temp_link_name, link_name) - except: + except Exception: if os.path.islink(temp_link_name): os.remove(temp_link_name) raise diff --git a/frappe/commands/scheduler.py b/frappe/commands/scheduler.py index ed6a0dea57..a39a604ece 100755 --- a/frappe/commands/scheduler.py +++ b/frappe/commands/scheduler.py @@ -15,7 +15,7 @@ def _is_scheduler_enabled(): enable_scheduler = ( cint(frappe.db.get_single_value("System Settings", "enable_scheduler")) and True or False ) - except: + except Exception: pass finally: frappe.db.close() diff --git a/frappe/core/doctype/doctype/test_doctype.py b/frappe/core/doctype/doctype/test_doctype.py index 569cf9af2f..5b0b575201 100644 --- a/frappe/core/doctype/doctype/test_doctype.py +++ b/frappe/core/doctype/doctype/test_doctype.py @@ -318,7 +318,7 @@ class TestDocType(unittest.TestCase): self.assertListEqual( test_doctype_json["field_order"], ["field_4", "field_5", "field_1", "field_2"] ) - except: + except Exception: raise finally: frappe.flags.allow_doctype_export = 0 diff --git a/frappe/core/doctype/user/user.py b/frappe/core/doctype/user/user.py index 531fd316b1..cfb2f4d871 100644 --- a/frappe/core/doctype/user/user.py +++ b/frappe/core/doctype/user/user.py @@ -586,7 +586,7 @@ class User(Document): for p in self.social_logins: if p.provider == provider: return p.userid - except: + except Exception: return None def set_social_login_userid(self, provider, userid, username=None): diff --git a/frappe/database/database.py b/frappe/database/database.py index c68368ba38..a52264ed6d 100644 --- a/frappe/database/database.py +++ b/frappe/database/database.py @@ -271,7 +271,7 @@ class Database(object): else: try: return self._cursor.mogrify(query, values) - except: # noqa: E722 + except Exception: return (query, values) def explain_query(self, query, values=None): diff --git a/frappe/desk/doctype/system_console/system_console.py b/frappe/desk/doctype/system_console/system_console.py index f1324403c3..063b3d37d0 100644 --- a/frappe/desk/doctype/system_console/system_console.py +++ b/frappe/desk/doctype/system_console/system_console.py @@ -19,7 +19,7 @@ class SystemConsole(Document): self.output = "\n".join(frappe.debug_log) elif self.type == "SQL": self.output = frappe.as_json(read_sql(self.console, as_dict=1)) - except: # noqa: E722 + except Exception: self.output = frappe.get_traceback() if self.commit: diff --git a/frappe/email/__init__.py b/frappe/email/__init__.py index fae60baebf..42fcb7b01a 100644 --- a/frappe/email/__init__.py +++ b/frappe/email/__init__.py @@ -17,24 +17,20 @@ def get_contact_list(txt, page_length=20): if cached_contacts: return cached_contacts[:page_length] - try: - match_conditions = build_match_conditions("Contact") - match_conditions = "and {0}".format(match_conditions) if match_conditions else "" - - out = frappe.db.sql( - """select email_id as value, - concat(first_name, ifnull(concat(' ',last_name), '' )) as description - from tabContact - where name like %(txt)s or email_id like %(txt)s - %(condition)s - limit %(page_length)s""", - {"txt": "%" + txt + "%", "condition": match_conditions, "page_length": page_length}, - as_dict=True, - ) - out = filter(None, out) - - except: - raise + match_conditions = build_match_conditions("Contact") + match_conditions = "and {0}".format(match_conditions) if match_conditions else "" + + out = frappe.db.sql( + """select email_id as value, + concat(first_name, ifnull(concat(' ',last_name), '' )) as description + from tabContact + where name like %(txt)s or email_id like %(txt)s + %(condition)s + limit %(page_length)s""", + {"txt": "%" + txt + "%", "condition": match_conditions, "page_length": page_length}, + as_dict=True, + ) + out = filter(None, out) update_contact_cache(out) diff --git a/frappe/email/doctype/newsletter/newsletter.py b/frappe/email/doctype/newsletter/newsletter.py index 18ca440738..6fcdce482f 100644 --- a/frappe/email/doctype/newsletter/newsletter.py +++ b/frappe/email/doctype/newsletter/newsletter.py @@ -66,7 +66,7 @@ class Newsletter(WebsiteGenerator): response = requests.head(url, verify=False, timeout=5) if response.status_code >= 400: broken_links.append(url) - except: + except Exception: broken_links.append(url) return broken_links diff --git a/frappe/email/doctype/notification/notification.py b/frappe/email/doctype/notification/notification.py index 5543ae6b5d..c8079f94e8 100644 --- a/frappe/email/doctype/notification/notification.py +++ b/frappe/email/doctype/notification/notification.py @@ -140,7 +140,7 @@ def get_context(context): if self.channel == "System Notification" or self.send_system_notification: self.create_system_notification(doc, context) - except: + except Exception: self.log_error("Failed to send Notification") if self.set_property_after_alert: diff --git a/frappe/email/receive.py b/frappe/email/receive.py index 12ab04eb4b..dd8273d778 100644 --- a/frappe/email/receive.py +++ b/frappe/email/receive.py @@ -377,7 +377,7 @@ class EmailServer: try: # retrieve headers incoming_mail = Email(b"\n".join(self.pop.top(msg_num, 5)[1])) - except: + except Exception: pass if incoming_mail: @@ -437,7 +437,7 @@ class Email: utc = email.utils.mktime_tz(email.utils.parsedate_tz(self.mail["Date"])) utc_dt = datetime.datetime.utcfromtimestamp(utc) self.date = convert_utc_to_user_timezone(utc_dt).strftime("%Y-%m-%d %H:%M:%S") - except: + except Exception: self.date = now() else: self.date = now() @@ -572,7 +572,7 @@ class Email: try: fname = fname.replace("\n", " ").replace("\r", "") fname = cstr(decode_header(fname)[0][0]) - except: + except Exception: fname = get_random_filename(content_type=content_type) else: fname = get_random_filename(content_type=content_type) diff --git a/frappe/installer.py b/frappe/installer.py index c8373ff06f..59c5dc6602 100644 --- a/frappe/installer.py +++ b/frappe/installer.py @@ -696,7 +696,7 @@ def extract_files(site_name, file_path): subprocess.check_output(["tar", "xvf", tar_path, "--strip", "2"], cwd=abs_site_path) elif file_path.endswith(".tgz"): subprocess.check_output(["tar", "zxvf", tar_path, "--strip", "2"], cwd=abs_site_path) - except: + except Exception: raise finally: frappe.destroy() diff --git a/frappe/integrations/doctype/razorpay_settings/razorpay_settings.py b/frappe/integrations/doctype/razorpay_settings/razorpay_settings.py index b48d21187c..b13319803f 100644 --- a/frappe/integrations/doctype/razorpay_settings/razorpay_settings.py +++ b/frappe/integrations/doctype/razorpay_settings/razorpay_settings.py @@ -141,8 +141,8 @@ class RazorpaySettings(Document): ) if not resp.get("id"): frappe.log_error(message=str(resp), title="Razorpay Failed while creating subscription") - except: - frappe.log_error(frappe.get_traceback()) + except Exception: + frappe.log_error() # failed pass @@ -181,10 +181,8 @@ class RazorpaySettings(Document): else: frappe.log_error(message=str(resp), title="Razorpay Failed while creating subscription") - except: - frappe.log_error(frappe.get_traceback()) - # failed - pass + except Exception: + frappe.log_error() def prepare_subscription_details(self, settings, **kwargs): if not kwargs.get("subscription_id"): @@ -283,10 +281,8 @@ class RazorpaySettings(Document): else: frappe.log_error(message=str(resp), title="Razorpay Payment not authorized") - except: - frappe.log_error(frappe.get_traceback()) - # failed - pass + except Exception: + frappe.log_error() status = frappe.flags.integration_request.status_code diff --git a/frappe/model/mapper.py b/frappe/model/mapper.py index 6a6522ad07..59f211e322 100644 --- a/frappe/model/mapper.py +++ b/frappe/model/mapper.py @@ -243,7 +243,7 @@ def map_fetch_fields(target_doc, df, no_copy_fields): if not linked_doc: try: linked_doc = frappe.get_doc(df.options, target_doc.get(df.fieldname)) - except: + except Exception: return val = linked_doc.get(source_fieldname) diff --git a/frappe/patches/v13_0/generate_theme_files_in_public_folder.py b/frappe/patches/v13_0/generate_theme_files_in_public_folder.py index 9b905a9bbb..29ddca1108 100644 --- a/frappe/patches/v13_0/generate_theme_files_in_public_folder.py +++ b/frappe/patches/v13_0/generate_theme_files_in_public_folder.py @@ -14,6 +14,6 @@ def execute(): try: doc.generate_bootstrap_theme() doc.save() - except: # noqa: E722 + except Exception: print("Ignoring....") print(frappe.get_traceback()) diff --git a/frappe/twofactor.py b/frappe/twofactor.py index 6d01331d7d..c803a5ff87 100644 --- a/frappe/twofactor.py +++ b/frappe/twofactor.py @@ -301,7 +301,7 @@ def send_token_via_sms(otpsecret, token=None, phone_no=None): """Send token as sms to user.""" try: from frappe.core.doctype.sms_settings.sms_settings import send_request - except: + except Exception: return False if not phone_no: diff --git a/frappe/utils/background_jobs.py b/frappe/utils/background_jobs.py index f49c641673..a7956717d4 100755 --- a/frappe/utils/background_jobs.py +++ b/frappe/utils/background_jobs.py @@ -166,7 +166,7 @@ def execute_job(site, method, event, job_name, kwargs, user=None, is_async=True, frappe.log_error(title=method_name) raise - except: + except Exception: frappe.db.rollback() frappe.log_error(title=method_name) frappe.db.commit() diff --git a/frappe/utils/data.py b/frappe/utils/data.py index 49f9ead437..dcc435e8fd 100644 --- a/frappe/utils/data.py +++ b/frappe/utils/data.py @@ -966,7 +966,7 @@ def floor(s): """ try: num = cint(math.floor(flt(s))) - except: + except Exception: num = 0 return num @@ -988,7 +988,7 @@ def ceil(s): """ try: num = cint(math.ceil(flt(s))) - except: + except Exception: num = 0 return num diff --git a/frappe/utils/pdf.py b/frappe/utils/pdf.py index 811a6511fd..ddab2f2b18 100644 --- a/frappe/utils/pdf.py +++ b/frappe/utils/pdf.py @@ -173,7 +173,7 @@ def read_options_from_html(html): match = pattern.findall(html) if match: options[attr] = str(match[-1][3]).strip() - except: + except Exception: pass return str(soup), options diff --git a/frappe/utils/scheduler.py b/frappe/utils/scheduler.py index 6444a2d079..48826b13c6 100755 --- a/frappe/utils/scheduler.py +++ b/frappe/utils/scheduler.py @@ -84,7 +84,7 @@ def enqueue_events_for_site(site): frappe.logger("scheduler").debug("Access denied for site {0}".format(site)) else: log_and_raise() - except: + except Exception: log_and_raise() finally: