sync_db_errors.py 1020 B

1234567891011121314151617181920212223242526
  1. # -*- coding: utf-8 -*-
  2. """同步脚本共用的数据库连接类异常判断(用于日志后放行外层循环)。"""
  3. import pymysql
  4. # 连接失败、断连、服务端关闭、连接数过多等,适合记录日志后由定时循环重试
  5. _DB_CONNECTION_ERR_CODES = frozenset(
  6. {
  7. 2002, # Can't connect to MySQL server
  8. 2003, # Can't connect to MySQL server (host)
  9. 2006, # MySQL server has gone away
  10. 2013, # Lost connection to MySQL server during query
  11. 2014, # Commands out of sync
  12. 1053, # Server shutdown in progress
  13. 1040, # Too many connections
  14. }
  15. )
  16. def is_database_connection_error(exc: BaseException) -> bool:
  17. """是否为连接/断连类问题(不中断 shell 循环,仅打日志)。"""
  18. if isinstance(exc, pymysql.err.InterfaceError):
  19. return True
  20. if isinstance(exc, pymysql.err.OperationalError):
  21. code = exc.args[0] if exc.args else None
  22. return code in _DB_CONNECTION_ERR_CODES
  23. return False