ElasticsearchException.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace Elastica\Exception;
  3. trigger_error('Elastica\Exception\ElasticsearchException is deprecated. Use Elastica\Exception\ResponseException::getResponse::getFullError instead.', E_USER_DEPRECATED);
  4. /**
  5. * Elasticsearch exception.
  6. *
  7. * @author Ian Babrou <ibobrik@gmail.com>
  8. */
  9. class ElasticsearchException extends \Exception implements ExceptionInterface
  10. {
  11. const REMOTE_TRANSPORT_EXCEPTION = 'RemoteTransportException';
  12. /**
  13. * @var string|null Elasticsearch exception name
  14. */
  15. private $_exception;
  16. /**
  17. * @var bool Whether exception was local to server node or remote
  18. */
  19. private $_isRemote = false;
  20. /**
  21. * @var array Error array
  22. */
  23. protected $_error = [];
  24. /**
  25. * Constructs elasticsearch exception.
  26. *
  27. * @param int $code Error code
  28. * @param string $error Error message from elasticsearch
  29. */
  30. public function __construct($code, $error)
  31. {
  32. $this->_parseError($error);
  33. parent::__construct($error, $code);
  34. }
  35. /**
  36. * Parse error message from elasticsearch.
  37. *
  38. * @param string $error Error message
  39. */
  40. protected function _parseError($error)
  41. {
  42. $errors = explode(']; nested: ', $error);
  43. if (1 == count($errors)) {
  44. $this->_exception = $this->_extractException($errors[0]);
  45. } else {
  46. if (self::REMOTE_TRANSPORT_EXCEPTION == $this->_extractException($errors[0])) {
  47. $this->_isRemote = true;
  48. $this->_exception = $this->_extractException($errors[1]);
  49. } else {
  50. $this->_exception = $this->_extractException($errors[0]);
  51. }
  52. }
  53. }
  54. /**
  55. * Extract exception name from error response.
  56. *
  57. * @param string $error
  58. *
  59. * @return string|null
  60. */
  61. protected function _extractException($error)
  62. {
  63. if (preg_match('/^(\w+)\[.*\]/', $error, $matches)) {
  64. return $matches[1];
  65. }
  66. return;
  67. }
  68. /**
  69. * Returns elasticsearch exception name.
  70. *
  71. * @return string|null
  72. */
  73. public function getExceptionName()
  74. {
  75. return $this->_exception;
  76. }
  77. /**
  78. * Returns whether exception was local to server node or remote.
  79. *
  80. * @return bool
  81. */
  82. public function isRemoteTransportException()
  83. {
  84. return $this->_isRemote;
  85. }
  86. /**
  87. * @return array Error array
  88. */
  89. public function getError()
  90. {
  91. return $this->_error;
  92. }
  93. }