pythonsqlalchemymysql-connector-python

'DatabaseError' is not being caught by mysql.connector.errors.DatabaseError python


I am using SQLAlchemy and mysql-connector. While executing a query, if I get mysql.connector.errors.DatabaseError I have used the exception provided by mysql.

The exception is going in the Exception block and not in the DatabaseError catch block.

Code

try:
    row_exists = None
    session_object = self.connect_to_database()
    # check if the value exists or not
    try:
        if session_object.query(
                exists().where(
                    ConnectorRequest.CR_Context_Key == input_context['Context_Key'])).scalar():
            row_exists = True
        else:
            row_exists = False
    except DatabaseError as mysql_error:
        logger.error('Error connecting to the MYSQL Server.Invalid database IP or Port provided' +
                     f'\nError-{str(mysql_error)}', exc_info=True)
    # close the session_object
    session_object.close()
    return row_exists
except Exception as error:
    logger.error('Error in exists query of the database' +
                 f'\nException - {str(error)}', exc_info=True)
(mysql.connector.errors.DatabaseError) 2003 (HY000): Can't connect to MySQL server on '10.10.1.00:3306' (101)
(Background on this error at: https://sqlalche.me/e/14/4xp6)
{"asctime": "2023-02-01 13:53:45,195", "levelname": "ERROR", "module": "Helper", "funcName": "check_if_file_is_already_processed", "process": 22216, 
"message": "Error in exists query of the database\nException - (mysql.connector.errors.DatabaseError) 2003 (HY000): Can't connect to MySQL server on '10.10.1.00:3306' (101)\n(Background on this error at: https://sqlalche.me/e/14/4xp6)", 
"exc_info": "Traceback (most recent call last):\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/connection_cext.py\", line 232, in _open_connection\n    self._cmysql.connect(**cnx_kwargs)\n_mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on '10.10.1.00:3306' (101)\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py\", line 3361, in _wrap_pool_connect\n    return fn()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 327, in connect\n    return _ConnectionFairy._checkout(self)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 894, in _checkout\n    fairy = _ConnectionRecord.checkout(pool)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 493, in checkout\n    rec = pool._do_get()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/impl.py\", line 146, in _do_get\n    self._dec_overflow()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py\", line 72, in __exit__\n    with_traceback=exc_tb,\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/compat.py\", line 211, in raise_\n    raise exception\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/impl.py\", line 143, in _do_get\n    return self._create_connection()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 273, in _create_connection\n    return _ConnectionRecord(self)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 388, in __init__\n    self.__connect()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 691, in __connect\n    pool.logger.debug(\"Error on connect(): %s\", e)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py\", line 72, in __exit__\n    with_traceback=exc_tb,\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/compat.py\", line 211, in raise_\n    raise exception\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 686, in __connect\n    self.dbapi_connection = connection = pool._invoke_creator(self)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/create.py\", line 578, in connect\n    return dialect.connect(*cargs, **cparams)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/default.py\", line 598, in connect\n    return self.dbapi.connect(*cargs, **cparams)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/__init__.py\", line 272, in connect\n    return CMySQLConnection(*args, **kwargs)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/connection_cext.py\", line 85, in __init__\n    self.connect(**kwargs)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/abstracts.py\", line 1003, in connect\n    self._open_connection()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/connection_cext.py\", line 235, in _open_connection\n    sqlstate=exc.sqlstate)\nmysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '10.10.1.00:3306' (101)\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n  File \"/home/usr/Workarea-2/usr/pycharm_project/toyota_finance_service/python_module/folder_listener_connector/folder_listener_connector/Helper.py\", line 155, in check_if_file_is_already_processed\n    ConnectorRequest.CR_Context_Key == input_context['Connector_Context_Key'])).scalar():\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py\", line 2893, in scalar\n    ret = self.one()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py\", line 2870, in one\n    return self._iter().one()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/orm/query.py\", line 2919, in _iter\n    execution_options={\"_sa_orm_load_options\": self.load_options},\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py\", line 1713, in execute\n    conn = self._connection_for_bind(bind)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py\", line 1553, in _connection_for_bind\n    engine, execution_options\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/orm/session.py\", line 747, in _connection_for_bind\n    conn = bind.connect()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py\", line 3315, in connect\n    return self._connection_cls(self, close_with_result=close_with_result)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py\", line 96, in __init__\n    else engine.raw_connection()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py\", line 3394, in raw_connection\n    return self._wrap_pool_connect(self.pool.connect, _connection)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py\", line 3365, in _wrap_pool_connect\n    e, dialect, self\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py\", line 2199, in _handle_dbapi_exception_noconnection\n    sqlalchemy_exception, with_traceback=exc_info[2], from_=e\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/compat.py\", line 211, in raise_\n    raise exception\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py\", line 3361, in _wrap_pool_connect\n    return fn()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 327, in connect\n    return _ConnectionFairy._checkout(self)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 894, in _checkout\n    fairy = _ConnectionRecord.checkout(pool)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 493, in checkout\n    rec = pool._do_get()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/impl.py\", line 146, in _do_get\n    self._dec_overflow()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py\", line 72, in __exit__\n    with_traceback=exc_tb,\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/compat.py\", line 211, in raise_\n    raise exception\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/impl.py\", line 143, in _do_get\n    return self._create_connection()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 273, in _create_connection\n    return _ConnectionRecord(self)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 388, in __init__\n    self.__connect()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 691, in __connect\n    pool.logger.debug(\"Error on connect(): %s\", e)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py\", line 72, in __exit__\n    with_traceback=exc_tb,\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/util/compat.py\", line 211, in raise_\n    raise exception\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/pool/base.py\", line 686, in __connect\n    self.dbapi_connection = connection = pool._invoke_creator(self)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/create.py\", line 578, in connect\n    return dialect.connect(*cargs, **cparams)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/sqlalchemy/engine/default.py\", line 598, in connect\n    return self.dbapi.connect(*cargs, **cparams)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/__init__.py\", line 272, in connect\n    return CMySQLConnection(*args, **kwargs)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/connection_cext.py\", line 85, in __init__\n    self.connect(**kwargs)\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/abstracts.py\", line 1003, in connect\n    self._open_connection()\n  File \"/home/usr/Workarea-2/usr/python_proj_env/folder_listener_connector_venv/lib/python3.6/site-packages/mysql/connector/connection_cext.py\", line 235, in _open_connection\n    sqlstate=exc.sqlstate)\nsqlalchemy.exc.DatabaseError: (mysql.connector.errors.DatabaseError) 2003 (HY000): Can't connect to MySQL server on '10.10.1.00:3306' (101)\n(Background on this error at: https://sqlalche.me/e/14/4xp6)"}

Solution

  • The exception is sqlalchemy.exc.DatabaseError; SQLAlchemy wraps the error from the DB-API connector (here MySQL-Connector) but displays the details from it.

    So you need to do

    from sqlalchemy.exc import DatabaseError
    
    ...
    
    try:
        # something
    except DatabaseError:
        # handle exception