Update bare exceptions to specify Exception.

This will keep us from accidentally catching program-exiting exceptions
like KeyboardInterupt and SystemExit.
This commit is contained in:
Toshio Kuratomi 2018-09-07 17:59:46 -07:00
commit 3fba006207
320 changed files with 659 additions and 656 deletions

View file

@ -116,7 +116,7 @@ def retry(retries=None, retry_pause=1):
raise Exception("Retry limit exceeded: %d" % retries)
try:
ret = f(*args, **kwargs)
except:
except Exception:
pass
if ret:
break

View file

@ -1069,7 +1069,7 @@ class AzureRMAuth(object):
for key in AZURE_CREDENTIAL_ENV_MAPPING:
try:
credentials[key] = config.get(profile, key, raw=True)
except:
except Exception:
pass
if credentials.get('subscription_id'):

View file

@ -553,7 +553,7 @@ def human_to_bytes(number, default_unit=None, isbits=False):
raise ValueError("human_to_bytes() can't interpret following string: %s" % str(number))
try:
num = float(m.group(1))
except:
except Exception:
raise ValueError("human_to_bytes() can't interpret following number: %s (original input string: %s)" % (m.group(1), number))
unit = m.group(2)
@ -566,7 +566,7 @@ def human_to_bytes(number, default_unit=None, isbits=False):
range_key = unit[0].upper()
try:
limit = SIZE_RANGES[range_key]
except:
except Exception:
raise ValueError("human_to_bytes() failed to convert %s (unit = %s). The suffix must be one of %s" % (number, unit, ", ".join(SIZE_RANGES.keys())))
# default value
@ -1028,7 +1028,7 @@ class AnsibleModule(object):
f = open('/proc/mounts', 'r')
mount_data = f.readlines()
f.close()
except:
except Exception:
return (False, None)
path_mount_point = self.find_mount_point(path)
for line in mount_data:
@ -1310,7 +1310,7 @@ class AnsibleModule(object):
output['attr_flags'] = res[1].replace('-', '').strip()
output['version'] = res[0].strip()
output['attributes'] = format_attributes(output['attr_flags'])
except:
except Exception:
pass
return output
@ -1820,7 +1820,7 @@ class AnsibleModule(object):
if value.startswith("{"):
try:
return json.loads(value)
except:
except Exception:
(result, exc) = self.safe_eval(value, dict(), include_exceptions=True)
if exc is not None:
raise TypeError('unable to evaluate string as dictionary')
@ -2163,7 +2163,7 @@ class AnsibleModule(object):
if not os.access(cwd, os.F_OK | os.R_OK):
raise Exception()
return cwd
except:
except Exception:
# we don't have access to the cwd, probably because of sudo.
# Try and move to a neutral location to prevent errors
for cwd in [self.tmpdir, os.path.expandvars('$HOME'), tempfile.gettempdir()]:
@ -2171,7 +2171,7 @@ class AnsibleModule(object):
if os.access(cwd, os.F_OK | os.R_OK):
os.chdir(cwd)
return cwd
except:
except Exception:
pass
# we won't error here, as it may *not* be a problem,
# and we don't want to break modules unnecessarily

View file

@ -28,7 +28,7 @@ def get_distribution():
distribution = 'Amazon'
else:
distribution = 'OtherLinux'
except:
except Exception:
# FIXME: MethodMissing, I assume?
distribution = platform.dist()[0].capitalize()
return distribution

View file

@ -49,7 +49,7 @@ try:
import boto3
import botocore
HAS_BOTO3 = True
except:
except Exception:
HAS_BOTO3 = False
try:

View file

@ -50,7 +50,7 @@ def api_wrapper(func):
module.fail_json(msg=e.message)
except core.exceptions.SystemNotFoundException as e:
module.fail_json(msg=e.message)
except:
except Exception:
raise
return __wrapper

View file

@ -135,7 +135,7 @@ def not_in_host_file(self, host):
hash.update(host)
if hash.digest() == kn_host.decode('base64'):
return False
except:
except Exception:
# invalid hashed host key, skip it
continue
else:
@ -164,7 +164,7 @@ def add_host_key(module, fqdn, port=22, key_type="rsa", create_dir=False):
if create_dir:
try:
os.makedirs(user_ssh_dir, int('700', 8))
except:
except Exception:
module.fail_json(msg="failed to create host key directory: %s" % user_ssh_dir)
else:
module.fail_json(msg="%s does not exist" % user_ssh_dir)

View file

@ -81,7 +81,7 @@ try:
from solidfire.models import Schedule, ScheduleInfo
HAS_SF_SDK = True
except:
except Exception:
HAS_SF_SDK = False
@ -124,7 +124,7 @@ def create_sf_connection(module, port=None):
try:
return_val = ElementFactory.create(hostname, username, password, port=port)
return return_val
except:
except Exception:
raise Exception("Unable to create SF connection")
else:
module.fail_json(msg="the python SolidFire SDK module is required")
@ -237,7 +237,7 @@ def request(url, data=None, headers=None, method='GET', use_proxy=True,
data = json.loads(raw_data)
else:
raw_data = None
except:
except Exception:
if ignore_errors:
pass
else:

View file

@ -6,7 +6,7 @@ try:
import solidfire.common
HAS_SF_SDK = True
except:
except Exception:
HAS_SF_SDK = False

View file

@ -78,7 +78,7 @@ def axapi_call(module, url, post=None):
data = {"response": {"status": "OK"}}
else:
data = {"response": {"status": "fail", "err": {"msg": raw_data}}}
except:
except Exception:
module.fail_json(msg="could not read the result from the host")
finally:
rsp.close()
@ -126,7 +126,7 @@ def axapi_call_v3(module, url, method=None, body=None, signature=None):
data = {"response": {"status": "OK"}}
else:
data = {"response": {"status": "fail", "err": {"msg": raw_data}}}
except:
except Exception:
module.fail_json(msg="could not read the result from the host")
finally:
rsp.close()

View file

@ -148,7 +148,7 @@ class ACIModule(object):
return true
elif bool_value is False:
return false
except:
except Exception:
# This provides backward compatibility to Ansible v2.4, deprecate in Ansible v2.8
if value == true:
self.module.deprecate("Boolean value '%s' is no longer valid, please use 'yes' as a boolean value." % value, '2.9')
@ -164,7 +164,7 @@ class ACIModule(object):
''' Return an ACI-compatible ISO8601 formatted time: 2123-12-12T00:00:00.000+00:00 '''
try:
return dt.isoformat(timespec='milliseconds')
except:
except Exception:
tz = dt.strftime('%z')
return '%s.%03d%s:%s' % (dt.strftime('%Y-%m-%dT%H:%M:%S'), dt.microsecond / 1000, tz[:3], tz[3:])
@ -231,7 +231,7 @@ class ACIModule(object):
try:
sig_key = load_privatekey(FILETYPE_PEM, open(self.params['private_key'], 'r').read())
except:
except Exception:
self.module.fail_json(msg='Cannot load private key %s' % self.params['private_key'])
# NOTE: ACI documentation incorrectly adds a space between method and path

View file

@ -183,7 +183,7 @@ class MSCModule(object):
elif self.status >= 400:
try:
payload = json.loads(resp.read())
except:
except Exception:
payload = json.loads(info['body'])
if 'code' in payload:
self.fail_json(msg='MSC Error {code}: {message}'.format(**payload), data=data, info=info, payload=payload)

View file

@ -147,7 +147,7 @@ def content_to_dict(module, content):
if not content_dict:
raise Exception()
except:
except Exception:
module.fail_json(msg="Unable to convert 'content' to a dict, please check if valid")
# replace the string with the dict
@ -163,7 +163,7 @@ def do_load_resource(module, collection, name):
try:
item = find_collection_item(collection, name, '')
except:
except Exception:
module.fail_json(msg="An error occurred while running 'find_collection_item'")
if item.exists:

View file

@ -38,7 +38,7 @@ try:
from ansible.module_utils.network.cnos import cnos_errorcodes
from ansible.module_utils.network.cnos import cnos_devicerules
HAS_LIB = True
except:
except Exception:
HAS_LIB = False
from distutils.cmd import Command
from ansible.module_utils._text import to_text
@ -1372,7 +1372,7 @@ def enterEnableModeForDevice(enablePassword, timeout, obj):
gotit = buff.find("#")
if(gotit != -1):
return retVal
except:
except Exception:
retVal = retVal + "\n Error-101"
flag = True
if(retVal == ""):
@ -1396,7 +1396,7 @@ def waitForDeviceResponse(command, prompt, timeout, obj):
gotit = buff.find(prompt)
if(gotit != -1):
flag = True
except:
except Exception:
# debugOutput(prompt)
if prompt == "(yes/no)?":
retVal = retVal

View file

@ -461,7 +461,7 @@ class Template:
if value:
try:
return ast.literal_eval(value)
except:
except Exception:
return str(value)
else:
return None

View file

@ -79,7 +79,7 @@ def backup(module, running_config):
if not os.path.exists(backup_path):
try:
os.mkdir(backup_path)
except:
except Exception:
module.fail_json(msg="Can't create directory {0} Permission denied ?".format(backup_path))
tstamp = time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime(time.time()))
if 0 < len(backup_filename):
@ -88,7 +88,7 @@ def backup(module, running_config):
filename = '%s/%s_config.%s' % (backup_path, module.params['host'], tstamp)
try:
open(filename, 'w').write(running_config)
except:
except Exception:
module.fail_json(msg="Can't create backup file {0} Permission denied ?".format(filename))

View file

@ -292,7 +292,7 @@ class MerakiModule(object):
body=json.loads(to_native(info['body'])))
try:
return json.loads(to_native(resp.read()))
except:
except Exception:
pass
def exit_json(self, **kwargs):

View file

@ -217,7 +217,7 @@ def rax_find_loadbalancer(module, rax_module, loadbalancer):
clb = rax_module.cloud_loadbalancers
try:
found = clb.get(loadbalancer)
except:
except Exception:
found = []
for lb in clb.list():
if loadbalancer == lb.name:

View file

@ -35,7 +35,7 @@ class RedfishUtils(object):
except URLError as e:
return {'ret': False, 'msg': "URL Error: %s" % e.reason}
# Almost all errors should be caught above, but just in case
except:
except Exception:
return {'ret': False, 'msg': "Unknown error"}
return {'ret': True, 'data': data}
@ -53,7 +53,7 @@ class RedfishUtils(object):
except URLError as e:
return {'ret': False, 'msg': "URL Error: %s" % e.reason}
# Almost all errors should be caught above, but just in case
except:
except Exception:
return {'ret': False, 'msg': "Unknown error"}
return {'ret': True, 'resp': resp}
@ -71,7 +71,7 @@ class RedfishUtils(object):
except URLError as e:
return {'ret': False, 'msg': "URL Error: %s" % e.reason}
# Almost all errors should be caught above, but just in case
except:
except Exception:
return {'ret': False, 'msg': "Unknown error"}
return {'ret': True, 'resp': resp}
@ -89,7 +89,7 @@ class RedfishUtils(object):
except URLError as e:
return {'ret': False, 'msg': "URL Error: %s" % e.reason}
# Almost all errors should be caught above, but just in case
except:
except Exception:
return {'ret': False, 'msg': "Unknown error"}
return {'ret': True, 'resp': resp}

View file

@ -31,7 +31,7 @@
try:
import ucsmsdk
HAS_UCSMSDK = True
except:
except Exception:
HAS_UCSMSDK = False
ucs_argument_spec = dict(

View file

@ -71,13 +71,13 @@ urllib_request.HTTPRedirectHandler.http_error_308 = urllib_request.HTTPRedirectH
try:
from ansible.module_utils.six.moves.urllib.parse import urlparse, urlunparse
HAS_URLPARSE = True
except:
except Exception:
HAS_URLPARSE = False
try:
import ssl
HAS_SSL = True
except:
except Exception:
HAS_SSL = False
try:
@ -436,7 +436,7 @@ def generic_urlparse(parts):
generic_parts['password'] = password
generic_parts['hostname'] = hostname
generic_parts['port'] = port
except:
except Exception:
generic_parts['username'] = None
generic_parts['password'] = None
generic_parts['hostname'] = parts[1]
@ -673,7 +673,7 @@ class SSLValidationHandler(urllib_request.BaseHandler):
(http_version, resp_code, msg) = re.match(br'(HTTP/\d\.\d) (\d\d\d) (.*)', response).groups()
if int(resp_code) not in valid_codes:
raise Exception
except:
except Exception:
raise ProxyError('Connection to proxy failed')
def detect_no_proxy(self, url):
@ -784,7 +784,7 @@ class SSLValidationHandler(urllib_request.BaseHandler):
# cleanup the temp file created, don't worry
# if it fails for some reason
os.remove(tmp_ca_cert_path)
except:
except Exception:
pass
try:
@ -792,7 +792,7 @@ class SSLValidationHandler(urllib_request.BaseHandler):
# if it fails for some reason
if to_add_ca_cert_path:
os.remove(to_add_ca_cert_path)
except:
except Exception:
pass
return req
@ -1305,7 +1305,7 @@ def fetch_url(module, url, data=None, headers=None, method=None,
try:
# Lowercase keys, to conform to py2 behavior, so that py3 and py2 are predictable
info.update(dict((k.lower(), v) for k, v in e.info().items()))
except:
except Exception:
pass
info.update({'msg': to_native(e), 'body': body, 'status': e.code})