CommunicationException.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Predis;
  11. use Exception;
  12. use Predis\Connection\NodeConnectionInterface;
  13. /**
  14. * Base exception class for network-related errors.
  15. *
  16. * @author Daniele Alessandri <suppakilla@gmail.com>
  17. */
  18. abstract class CommunicationException extends PredisException
  19. {
  20. private $connection;
  21. /**
  22. * @param NodeConnectionInterface $connection Connection that generated the exception.
  23. * @param string $message Error message.
  24. * @param int $code Error code.
  25. * @param Exception $innerException Inner exception for wrapping the original error.
  26. */
  27. public function __construct(
  28. NodeConnectionInterface $connection,
  29. $message = null,
  30. $code = null,
  31. Exception $innerException = null
  32. ) {
  33. parent::__construct($message, $code, $innerException);
  34. $this->connection = $connection;
  35. }
  36. /**
  37. * Gets the connection that generated the exception.
  38. *
  39. * @return NodeConnectionInterface
  40. */
  41. public function getConnection()
  42. {
  43. return $this->connection;
  44. }
  45. /**
  46. * Indicates if the receiver should reset the underlying connection.
  47. *
  48. * @return bool
  49. */
  50. public function shouldResetConnection()
  51. {
  52. return true;
  53. }
  54. /**
  55. * Helper method to handle exceptions generated by a connection object.
  56. *
  57. * @param CommunicationException $exception Exception.
  58. *
  59. * @throws CommunicationException
  60. */
  61. public static function handle(CommunicationException $exception)
  62. {
  63. if ($exception->shouldResetConnection()) {
  64. $connection = $exception->getConnection();
  65. if ($connection->isConnected()) {
  66. $connection->disconnect();
  67. }
  68. }
  69. throw $exception;
  70. }
  71. }