errors.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # Copyright 2009-present MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Exceptions raised by PyMongo."""
  15. import sys
  16. from bson.errors import *
  17. try:
  18. # CPython 3.7+
  19. from ssl import SSLCertVerificationError as CertificateError
  20. except ImportError:
  21. try:
  22. from ssl import CertificateError
  23. except ImportError:
  24. class CertificateError(ValueError):
  25. pass
  26. class PyMongoError(Exception):
  27. """Base class for all PyMongo exceptions."""
  28. def __init__(self, message='', error_labels=None):
  29. super(PyMongoError, self).__init__(message)
  30. self._message = message
  31. self._error_labels = set(error_labels or [])
  32. def has_error_label(self, label):
  33. """Return True if this error contains the given label.
  34. .. versionadded:: 3.7
  35. """
  36. return label in self._error_labels
  37. def _add_error_label(self, label):
  38. """Add the given label to this error."""
  39. self._error_labels.add(label)
  40. def _remove_error_label(self, label):
  41. """Remove the given label from this error."""
  42. self._error_labels.discard(label)
  43. if sys.version_info[0] == 2:
  44. def __str__(self):
  45. if isinstance(self._message, unicode):
  46. return self._message.encode('utf-8', errors='replace')
  47. return str(self._message)
  48. def __unicode__(self):
  49. if isinstance(self._message, unicode):
  50. return self._message
  51. return unicode(self._message, 'utf-8', errors='replace')
  52. class ProtocolError(PyMongoError):
  53. """Raised for failures related to the wire protocol."""
  54. class ConnectionFailure(PyMongoError):
  55. """Raised when a connection to the database cannot be made or is lost."""
  56. class AutoReconnect(ConnectionFailure):
  57. """Raised when a connection to the database is lost and an attempt to
  58. auto-reconnect will be made.
  59. In order to auto-reconnect you must handle this exception, recognizing that
  60. the operation which caused it has not necessarily succeeded. Future
  61. operations will attempt to open a new connection to the database (and
  62. will continue to raise this exception until the first successful
  63. connection is made).
  64. Subclass of :exc:`~pymongo.errors.ConnectionFailure`.
  65. """
  66. def __init__(self, message='', errors=None):
  67. error_labels = None
  68. if errors is not None and isinstance(errors, dict):
  69. error_labels = errors.get('errorLabels')
  70. super(AutoReconnect, self).__init__(message, error_labels)
  71. self.errors = self.details = errors or []
  72. class NetworkTimeout(AutoReconnect):
  73. """An operation on an open connection exceeded socketTimeoutMS.
  74. The remaining connections in the pool stay open. In the case of a write
  75. operation, you cannot know whether it succeeded or failed.
  76. Subclass of :exc:`~pymongo.errors.AutoReconnect`.
  77. """
  78. def _format_detailed_error(message, details):
  79. if details is not None:
  80. message = "%s, full error: %s" % (message, details)
  81. if sys.version_info[0] == 2 and isinstance(message, unicode):
  82. message = message.encode('utf-8', errors='replace')
  83. return message
  84. class NotMasterError(AutoReconnect):
  85. """**DEPRECATED** - The server responded "not master" or
  86. "node is recovering".
  87. This exception has been deprecated and will be removed in PyMongo 4.0.
  88. Use :exc:`~pymongo.errors.NotPrimaryError` instead.
  89. .. versionchanged:: 3.12
  90. Deprecated. Use :exc:`~pymongo.errors.NotPrimaryError` instead.
  91. """
  92. def __init__(self, message='', errors=None):
  93. super(NotMasterError, self).__init__(
  94. _format_detailed_error(message, errors), errors=errors)
  95. class NotPrimaryError(NotMasterError):
  96. """The server responded "not primary" or "node is recovering".
  97. These errors result from a query, write, or command. The operation failed
  98. because the client thought it was using the primary but the primary has
  99. stepped down, or the client thought it was using a healthy secondary but
  100. the secondary is stale and trying to recover.
  101. The client launches a refresh operation on a background thread, to update
  102. its view of the server as soon as possible after throwing this exception.
  103. Subclass of :exc:`~pymongo.errors.AutoReconnect`.
  104. .. versionadded:: 3.12
  105. """
  106. def __init__(self, message='', errors=None):
  107. super(NotPrimaryError, self).__init__(message, errors=errors)
  108. class ServerSelectionTimeoutError(AutoReconnect):
  109. """Thrown when no MongoDB server is available for an operation
  110. If there is no suitable server for an operation PyMongo tries for
  111. ``serverSelectionTimeoutMS`` (default 30 seconds) to find one, then
  112. throws this exception. For example, it is thrown after attempting an
  113. operation when PyMongo cannot connect to any server, or if you attempt
  114. an insert into a replica set that has no primary and does not elect one
  115. within the timeout window, or if you attempt to query with a Read
  116. Preference that the replica set cannot satisfy.
  117. """
  118. class ConfigurationError(PyMongoError):
  119. """Raised when something is incorrectly configured.
  120. """
  121. class OperationFailure(PyMongoError):
  122. """Raised when a database operation fails.
  123. .. versionadded:: 2.7
  124. The :attr:`details` attribute.
  125. """
  126. def __init__(self, error, code=None, details=None, max_wire_version=None):
  127. error_labels = None
  128. if details is not None:
  129. error_labels = details.get('errorLabels')
  130. super(OperationFailure, self).__init__(
  131. _format_detailed_error(error, details), error_labels=error_labels)
  132. self.__code = code
  133. self.__details = details
  134. self.__max_wire_version = max_wire_version
  135. @property
  136. def _max_wire_version(self):
  137. return self.__max_wire_version
  138. @property
  139. def code(self):
  140. """The error code returned by the server, if any.
  141. """
  142. return self.__code
  143. @property
  144. def details(self):
  145. """The complete error document returned by the server.
  146. Depending on the error that occurred, the error document
  147. may include useful information beyond just the error
  148. message. When connected to a mongos the error document
  149. may contain one or more subdocuments if errors occurred
  150. on multiple shards.
  151. """
  152. return self.__details
  153. class CursorNotFound(OperationFailure):
  154. """Raised while iterating query results if the cursor is
  155. invalidated on the server.
  156. .. versionadded:: 2.7
  157. """
  158. class ExecutionTimeout(OperationFailure):
  159. """Raised when a database operation times out, exceeding the $maxTimeMS
  160. set in the query or command option.
  161. .. note:: Requires server version **>= 2.6.0**
  162. .. versionadded:: 2.7
  163. """
  164. class WriteConcernError(OperationFailure):
  165. """Base exception type for errors raised due to write concern.
  166. .. versionadded:: 3.0
  167. """
  168. class WriteError(OperationFailure):
  169. """Base exception type for errors raised during write operations.
  170. .. versionadded:: 3.0
  171. """
  172. class WTimeoutError(WriteConcernError):
  173. """Raised when a database operation times out (i.e. wtimeout expires)
  174. before replication completes.
  175. With newer versions of MongoDB the `details` attribute may include
  176. write concern fields like 'n', 'updatedExisting', or 'writtenTo'.
  177. .. versionadded:: 2.7
  178. """
  179. class DuplicateKeyError(WriteError):
  180. """Raised when an insert or update fails due to a duplicate key error."""
  181. class BulkWriteError(OperationFailure):
  182. """Exception class for bulk write errors.
  183. .. versionadded:: 2.7
  184. """
  185. def __init__(self, results):
  186. super(BulkWriteError, self).__init__(
  187. "batch op errors occurred", 65, results)
  188. def __reduce__(self):
  189. return self.__class__, (self.details,)
  190. class InvalidOperation(PyMongoError):
  191. """Raised when a client attempts to perform an invalid operation."""
  192. class InvalidName(PyMongoError):
  193. """Raised when an invalid name is used."""
  194. class CollectionInvalid(PyMongoError):
  195. """Raised when collection validation fails."""
  196. class InvalidURI(ConfigurationError):
  197. """Raised when trying to parse an invalid mongodb URI."""
  198. class ExceededMaxWaiters(PyMongoError):
  199. """Raised when a thread tries to get a connection from a pool and
  200. ``maxPoolSize * waitQueueMultiple`` threads are already waiting.
  201. .. versionadded:: 2.6
  202. """
  203. pass
  204. class DocumentTooLarge(InvalidDocument):
  205. """Raised when an encoded document is too large for the connected server.
  206. """
  207. pass
  208. class EncryptionError(PyMongoError):
  209. """Raised when encryption or decryption fails.
  210. This error always wraps another exception which can be retrieved via the
  211. :attr:`cause` property.
  212. .. versionadded:: 3.9
  213. """
  214. def __init__(self, cause):
  215. super(EncryptionError, self).__init__(str(cause))
  216. self.__cause = cause
  217. @property
  218. def cause(self):
  219. """The exception that caused this encryption or decryption error."""
  220. return self.__cause
  221. class _OperationCancelled(AutoReconnect):
  222. """Internal error raised when a socket operation is cancelled.
  223. """
  224. pass