Don't access deprecated Exception.message attribute. (#32556)

* Don't access deprecated Exception.message attribute.

To avoid a deprecation warning message in logs.
There is a new function salt.exceptions.get_error_message(e) instead.

* Fixed module docs test.
This commit is contained in:
Dmitry Kuzmenko 2016-04-18 19:51:43 +03:00 committed by Mike Place
parent 5d1e9a478b
commit 21081b1e88
9 changed files with 39 additions and 20 deletions

View File

@ -50,7 +50,7 @@ try:
except ImportError as exc: except ImportError as exc:
if exc.args[0] != 'No module named _msgpack': if exc.args[0] != 'No module named _msgpack':
raise raise
from salt.exceptions import SaltSystemExit from salt.exceptions import SaltSystemExit, get_error_message
# Let's instantiate logger using salt.log.setup.logging.getLogger() so pylint # Let's instantiate logger using salt.log.setup.logging.getLogger() so pylint
@ -97,7 +97,7 @@ class DaemonsMixin(object): # pylint: disable=no-init
:return: :return:
''' '''
logger.exception('Failed to create environment for {d_name}: {reason}'.format( logger.exception('Failed to create environment for {d_name}: {reason}'.format(
d_name=self.__class__.__name__, reason=error.message)) d_name=self.__class__.__name__, reason=get_error_message(error)))
sys.exit(error.errno) sys.exit(error.errno)

View File

@ -15,6 +15,13 @@ import salt.defaults.exitcodes
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
def get_error_message(error):
'''
Get human readable message from Python Exception
'''
return error.args[0] if error.args else ''
class SaltException(Exception): class SaltException(Exception):
''' '''
Base exception class; all Salt-specific exceptions should subclass this Base exception class; all Salt-specific exceptions should subclass this

View File

@ -12,6 +12,7 @@ import json
import logging import logging
import salt.utils import salt.utils
import salt.utils.http import salt.utils.http
from salt.exceptions import get_error_message
__proxyenabled__ = ['chronos'] __proxyenabled__ = ['chronos']
@ -109,10 +110,10 @@ def update_job(name, config):
log.debug('update response: %s', response) log.debug('update response: %s', response)
return {'success': True} return {'success': True}
except Exception as ex: except Exception as ex:
log.error('unable to update chronos job: %s', ex.message) log.error('unable to update chronos job: %s', get_error_message(ex))
return { return {
'exception': { 'exception': {
'message': ex.message, 'message': get_error_message(ex),
} }
} }

View File

@ -52,7 +52,7 @@ import salt.utils.filebuffer
import salt.utils.files import salt.utils.files
import salt.utils.atomicfile import salt.utils.atomicfile
import salt.utils.url import salt.utils.url
from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.exceptions import CommandExecutionError, SaltInvocationError, get_error_message as _get_error_message
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -1356,7 +1356,7 @@ def _regex_to_static(src, regex):
try: try:
src = re.search(regex, src) src = re.search(regex, src)
except Exception as ex: except Exception as ex:
raise CommandExecutionError("{0}: '{1}'".format(ex.message, regex)) raise CommandExecutionError("{0}: '{1}'".format(_get_error_message(ex), regex))
return src and src.group() or regex return src and src.group() or regex

View File

@ -12,6 +12,7 @@ import json
import logging import logging
import salt.utils import salt.utils
import salt.utils.http import salt.utils.http
from salt.exceptions import get_error_message
__proxyenabled__ = ['marathon'] __proxyenabled__ = ['marathon']
@ -112,10 +113,10 @@ def update_app(id, config):
log.debug('update response: %s', response) log.debug('update response: %s', response)
return response['dict'] return response['dict']
except Exception as ex: except Exception as ex:
log.error('unable to update marathon app: %s', ex.message) log.error('unable to update marathon app: %s', get_error_message(ex))
return { return {
'exception': { 'exception': {
'message': ex.message, 'message': get_error_message(ex),
} }
} }

View File

@ -22,6 +22,7 @@ import json
# Import salt libs # Import salt libs
from salt.ext.six import string_types from salt.ext.six import string_types
from salt.exceptions import get_error_message as _get_error_message
# Import third party libs # Import third party libs
@ -428,6 +429,16 @@ def insert(objects, collection, user=None, password=None,
def find(collection, query=None, user=None, password=None, def find(collection, query=None, user=None, password=None,
host=None, port=None, database='admin'): host=None, port=None, database='admin'):
"""
Find an object or list of objects in a collection
CLI Example:
.. code-block:: bash
salt '*' mongodb.find mycollection '[{"foo": "FOO", "bar": "BAR"}]' <user> <password> <host> <port> <database>
"""
conn = _connect(user, password, host, port, database) conn = _connect(user, password, host, port, database)
if not conn: if not conn:
return 'Failed to connect to mongo database' return 'Failed to connect to mongo database'
@ -444,7 +455,7 @@ def find(collection, query=None, user=None, password=None,
ret = col.find(query) ret = col.find(query)
return list(ret) return list(ret)
except pymongo.errors.PyMongoError as err: except pymongo.errors.PyMongoError as err:
log.error("Removing objects failed with error: %s", err) log.error("Searching objects failed with error: %s", err)
return err return err
@ -467,7 +478,7 @@ def remove(collection, query=None, user=None, password=None,
try: try:
query = _to_dict(query) query = _to_dict(query)
except Exception as err: except Exception as err:
return err.message return _get_error_message(err)
try: try:
log.info("Removing %r from %s", query, collection) log.info("Removing %r from %s", query, collection)
@ -476,5 +487,5 @@ def remove(collection, query=None, user=None, password=None,
ret = col.remove(query, w=w) ret = col.remove(query, w=w)
return "{0} objects removed".format(ret['n']) return "{0} objects removed".format(ret['n'])
except pymongo.errors.PyMongoError as err: except pymongo.errors.PyMongoError as err:
log.error("Removing objects failed with error: %s", err.message) log.error("Removing objects failed with error: %s", _get_error_message(err))
return err.message return _get_error_message(err)

View File

@ -26,6 +26,7 @@ from salt.modules.inspectlib.exceptions import (InspectorQueryException,
import salt.utils import salt.utils
import salt.utils.fsutils import salt.utils.fsutils
from salt.exceptions import CommandExecutionError from salt.exceptions import CommandExecutionError
from salt.exceptions import get_error_message as _get_error_message
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -87,7 +88,7 @@ def inspect(mode='all', priority=19, **kwargs):
except InspectorSnapshotException as ex: except InspectorSnapshotException as ex:
raise CommandExecutionError(ex) raise CommandExecutionError(ex)
except Exception as ex: except Exception as ex:
log.error(ex.message) log.error(_get_error_message(ex))
raise Exception(ex) raise Exception(ex)
@ -152,5 +153,5 @@ def query(scope, **kwargs):
except InspectorQueryException as ex: except InspectorQueryException as ex:
raise CommandExecutionError(ex) raise CommandExecutionError(ex)
except Exception as ex: except Exception as ex:
log.error(ex.message) log.error(_get_error_message(ex))
raise Exception(ex) raise Exception(ex)

View File

@ -14,7 +14,7 @@ import traceback
from random import randint from random import randint
# Import salt libs # Import salt libs
from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError from salt.exceptions import SaltSystemExit, SaltClientError, SaltReqTimeoutError, get_error_message
import salt.defaults.exitcodes # pylint: disable=unused-import import salt.defaults.exitcodes # pylint: disable=unused-import
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -81,7 +81,7 @@ def minion_process(queue):
minion.start() minion.start()
except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc: except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit) as exc:
log.error( log.error(
'Minion failed to start: {0}'.format(exc.message), 'Minion failed to start: {0}'.format(get_error_message(exc)),
exc_info=True exc_info=True
) )
restart = True restart = True

View File

@ -25,7 +25,7 @@ import salt.utils.itertools
import salt.utils.url import salt.utils.url
import salt.fileserver import salt.fileserver
from salt.utils.process import os_is_running as pid_exists from salt.utils.process import os_is_running as pid_exists
from salt.exceptions import FileserverConfigError, GitLockError from salt.exceptions import FileserverConfigError, GitLockError, get_error_message
from salt.utils.event import tagify from salt.utils.event import tagify
# Import third party libs # Import third party libs
@ -1295,9 +1295,7 @@ class Pygit2(GitProvider):
try: try:
fetch_results = origin.fetch(**fetch_kwargs) fetch_results = origin.fetch(**fetch_kwargs)
except GitError as exc: except GitError as exc:
# Using exc.__str__() here to avoid deprecation warning exc_str = get_error_message(exc).lower()
# when referencing exc.message
exc_str = exc.__str__().lower()
if 'unsupported url protocol' in exc_str \ if 'unsupported url protocol' in exc_str \
and isinstance(self.credentials, pygit2.Keypair): and isinstance(self.credentials, pygit2.Keypair):
log.error( log.error(