Browse Source

fix: remove bare exception catching

A bare except catches lots of things (like generator iteration end) and should never be used.
version-14
Ankush Menat 2 years ago
parent
commit
d35d7ffbe2
20 changed files with 40 additions and 49 deletions
  1. +0
    -1
      .github/helper/flake8.conf
  2. +1
    -1
      frappe/build.py
  3. +1
    -1
      frappe/commands/scheduler.py
  4. +1
    -1
      frappe/core/doctype/doctype/test_doctype.py
  5. +1
    -1
      frappe/core/doctype/user/user.py
  6. +1
    -1
      frappe/database/database.py
  7. +1
    -1
      frappe/desk/doctype/system_console/system_console.py
  8. +14
    -18
      frappe/email/__init__.py
  9. +1
    -1
      frappe/email/doctype/newsletter/newsletter.py
  10. +1
    -1
      frappe/email/doctype/notification/notification.py
  11. +3
    -3
      frappe/email/receive.py
  12. +1
    -1
      frappe/installer.py
  13. +6
    -10
      frappe/integrations/doctype/razorpay_settings/razorpay_settings.py
  14. +1
    -1
      frappe/model/mapper.py
  15. +1
    -1
      frappe/patches/v13_0/generate_theme_files_in_public_folder.py
  16. +1
    -1
      frappe/twofactor.py
  17. +1
    -1
      frappe/utils/background_jobs.py
  18. +2
    -2
      frappe/utils/data.py
  19. +1
    -1
      frappe/utils/pdf.py
  20. +1
    -1
      frappe/utils/scheduler.py

+ 0
- 1
.github/helper/flake8.conf View File

@@ -69,7 +69,6 @@ ignore =
F841, F841,
E713, E713,
E712, E712,
E722,




max-line-length = 200 max-line-length = 200


+ 1
- 1
frappe/build.py View File

@@ -205,7 +205,7 @@ def symlink(target, link_name, overwrite=False):
os.replace(temp_link_name, link_name) os.replace(temp_link_name, link_name)
except AttributeError: except AttributeError:
os.renames(temp_link_name, link_name) os.renames(temp_link_name, link_name)
except:
except Exception:
if os.path.islink(temp_link_name): if os.path.islink(temp_link_name):
os.remove(temp_link_name) os.remove(temp_link_name)
raise raise


+ 1
- 1
frappe/commands/scheduler.py View File

@@ -15,7 +15,7 @@ def _is_scheduler_enabled():
enable_scheduler = ( enable_scheduler = (
cint(frappe.db.get_single_value("System Settings", "enable_scheduler")) and True or False cint(frappe.db.get_single_value("System Settings", "enable_scheduler")) and True or False
) )
except:
except Exception:
pass pass
finally: finally:
frappe.db.close() frappe.db.close()


+ 1
- 1
frappe/core/doctype/doctype/test_doctype.py View File

@@ -318,7 +318,7 @@ class TestDocType(unittest.TestCase):
self.assertListEqual( self.assertListEqual(
test_doctype_json["field_order"], ["field_4", "field_5", "field_1", "field_2"] test_doctype_json["field_order"], ["field_4", "field_5", "field_1", "field_2"]
) )
except:
except Exception:
raise raise
finally: finally:
frappe.flags.allow_doctype_export = 0 frappe.flags.allow_doctype_export = 0


+ 1
- 1
frappe/core/doctype/user/user.py View File

@@ -586,7 +586,7 @@ class User(Document):
for p in self.social_logins: for p in self.social_logins:
if p.provider == provider: if p.provider == provider:
return p.userid return p.userid
except:
except Exception:
return None return None


def set_social_login_userid(self, provider, userid, username=None): def set_social_login_userid(self, provider, userid, username=None):


+ 1
- 1
frappe/database/database.py View File

@@ -271,7 +271,7 @@ class Database(object):
else: else:
try: try:
return self._cursor.mogrify(query, values) return self._cursor.mogrify(query, values)
except: # noqa: E722
except Exception:
return (query, values) return (query, values)


def explain_query(self, query, values=None): def explain_query(self, query, values=None):


+ 1
- 1
frappe/desk/doctype/system_console/system_console.py View File

@@ -19,7 +19,7 @@ class SystemConsole(Document):
self.output = "\n".join(frappe.debug_log) self.output = "\n".join(frappe.debug_log)
elif self.type == "SQL": elif self.type == "SQL":
self.output = frappe.as_json(read_sql(self.console, as_dict=1)) self.output = frappe.as_json(read_sql(self.console, as_dict=1))
except: # noqa: E722
except Exception:
self.output = frappe.get_traceback() self.output = frappe.get_traceback()


if self.commit: if self.commit:


+ 14
- 18
frappe/email/__init__.py View File

@@ -17,24 +17,20 @@ def get_contact_list(txt, page_length=20):
if cached_contacts: if cached_contacts:
return cached_contacts[:page_length] 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) update_contact_cache(out)




+ 1
- 1
frappe/email/doctype/newsletter/newsletter.py View File

@@ -66,7 +66,7 @@ class Newsletter(WebsiteGenerator):
response = requests.head(url, verify=False, timeout=5) response = requests.head(url, verify=False, timeout=5)
if response.status_code >= 400: if response.status_code >= 400:
broken_links.append(url) broken_links.append(url)
except:
except Exception:
broken_links.append(url) broken_links.append(url)
return broken_links return broken_links




+ 1
- 1
frappe/email/doctype/notification/notification.py View File

@@ -140,7 +140,7 @@ def get_context(context):
if self.channel == "System Notification" or self.send_system_notification: if self.channel == "System Notification" or self.send_system_notification:
self.create_system_notification(doc, context) self.create_system_notification(doc, context)


except:
except Exception:
self.log_error("Failed to send Notification") self.log_error("Failed to send Notification")


if self.set_property_after_alert: if self.set_property_after_alert:


+ 3
- 3
frappe/email/receive.py View File

@@ -377,7 +377,7 @@ class EmailServer:
try: try:
# retrieve headers # retrieve headers
incoming_mail = Email(b"\n".join(self.pop.top(msg_num, 5)[1])) incoming_mail = Email(b"\n".join(self.pop.top(msg_num, 5)[1]))
except:
except Exception:
pass pass


if incoming_mail: if incoming_mail:
@@ -437,7 +437,7 @@ class Email:
utc = email.utils.mktime_tz(email.utils.parsedate_tz(self.mail["Date"])) utc = email.utils.mktime_tz(email.utils.parsedate_tz(self.mail["Date"]))
utc_dt = datetime.datetime.utcfromtimestamp(utc) utc_dt = datetime.datetime.utcfromtimestamp(utc)
self.date = convert_utc_to_user_timezone(utc_dt).strftime("%Y-%m-%d %H:%M:%S") self.date = convert_utc_to_user_timezone(utc_dt).strftime("%Y-%m-%d %H:%M:%S")
except:
except Exception:
self.date = now() self.date = now()
else: else:
self.date = now() self.date = now()
@@ -572,7 +572,7 @@ class Email:
try: try:
fname = fname.replace("\n", " ").replace("\r", "") fname = fname.replace("\n", " ").replace("\r", "")
fname = cstr(decode_header(fname)[0][0]) fname = cstr(decode_header(fname)[0][0])
except:
except Exception:
fname = get_random_filename(content_type=content_type) fname = get_random_filename(content_type=content_type)
else: else:
fname = get_random_filename(content_type=content_type) fname = get_random_filename(content_type=content_type)


+ 1
- 1
frappe/installer.py View File

@@ -696,7 +696,7 @@ def extract_files(site_name, file_path):
subprocess.check_output(["tar", "xvf", tar_path, "--strip", "2"], cwd=abs_site_path) subprocess.check_output(["tar", "xvf", tar_path, "--strip", "2"], cwd=abs_site_path)
elif file_path.endswith(".tgz"): elif file_path.endswith(".tgz"):
subprocess.check_output(["tar", "zxvf", tar_path, "--strip", "2"], cwd=abs_site_path) subprocess.check_output(["tar", "zxvf", tar_path, "--strip", "2"], cwd=abs_site_path)
except:
except Exception:
raise raise
finally: finally:
frappe.destroy() frappe.destroy()


+ 6
- 10
frappe/integrations/doctype/razorpay_settings/razorpay_settings.py View File

@@ -141,8 +141,8 @@ class RazorpaySettings(Document):
) )
if not resp.get("id"): if not resp.get("id"):
frappe.log_error(message=str(resp), title="Razorpay Failed while creating subscription") 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 # failed
pass pass


@@ -181,10 +181,8 @@ class RazorpaySettings(Document):
else: else:
frappe.log_error(message=str(resp), title="Razorpay Failed while creating subscription") 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): def prepare_subscription_details(self, settings, **kwargs):
if not kwargs.get("subscription_id"): if not kwargs.get("subscription_id"):
@@ -283,10 +281,8 @@ class RazorpaySettings(Document):
else: else:
frappe.log_error(message=str(resp), title="Razorpay Payment not authorized") 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 status = frappe.flags.integration_request.status_code




+ 1
- 1
frappe/model/mapper.py View File

@@ -243,7 +243,7 @@ def map_fetch_fields(target_doc, df, no_copy_fields):
if not linked_doc: if not linked_doc:
try: try:
linked_doc = frappe.get_doc(df.options, target_doc.get(df.fieldname)) linked_doc = frappe.get_doc(df.options, target_doc.get(df.fieldname))
except:
except Exception:
return return


val = linked_doc.get(source_fieldname) val = linked_doc.get(source_fieldname)


+ 1
- 1
frappe/patches/v13_0/generate_theme_files_in_public_folder.py View File

@@ -14,6 +14,6 @@ def execute():
try: try:
doc.generate_bootstrap_theme() doc.generate_bootstrap_theme()
doc.save() doc.save()
except: # noqa: E722
except Exception:
print("Ignoring....") print("Ignoring....")
print(frappe.get_traceback()) print(frappe.get_traceback())

+ 1
- 1
frappe/twofactor.py View File

@@ -301,7 +301,7 @@ def send_token_via_sms(otpsecret, token=None, phone_no=None):
"""Send token as sms to user.""" """Send token as sms to user."""
try: try:
from frappe.core.doctype.sms_settings.sms_settings import send_request from frappe.core.doctype.sms_settings.sms_settings import send_request
except:
except Exception:
return False return False


if not phone_no: if not phone_no:


+ 1
- 1
frappe/utils/background_jobs.py View File

@@ -166,7 +166,7 @@ def execute_job(site, method, event, job_name, kwargs, user=None, is_async=True,
frappe.log_error(title=method_name) frappe.log_error(title=method_name)
raise raise


except:
except Exception:
frappe.db.rollback() frappe.db.rollback()
frappe.log_error(title=method_name) frappe.log_error(title=method_name)
frappe.db.commit() frappe.db.commit()


+ 2
- 2
frappe/utils/data.py View File

@@ -966,7 +966,7 @@ def floor(s):
""" """
try: try:
num = cint(math.floor(flt(s))) num = cint(math.floor(flt(s)))
except:
except Exception:
num = 0 num = 0
return num return num


@@ -988,7 +988,7 @@ def ceil(s):
""" """
try: try:
num = cint(math.ceil(flt(s))) num = cint(math.ceil(flt(s)))
except:
except Exception:
num = 0 num = 0
return num return num




+ 1
- 1
frappe/utils/pdf.py View File

@@ -173,7 +173,7 @@ def read_options_from_html(html):
match = pattern.findall(html) match = pattern.findall(html)
if match: if match:
options[attr] = str(match[-1][3]).strip() options[attr] = str(match[-1][3]).strip()
except:
except Exception:
pass pass


return str(soup), options return str(soup), options


+ 1
- 1
frappe/utils/scheduler.py View File

@@ -84,7 +84,7 @@ def enqueue_events_for_site(site):
frappe.logger("scheduler").debug("Access denied for site {0}".format(site)) frappe.logger("scheduler").debug("Access denied for site {0}".format(site))
else: else:
log_and_raise() log_and_raise()
except:
except Exception:
log_and_raise() log_and_raise()


finally: finally:


Loading…
Cancel
Save