CommunicationException.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 Predis\Connection\SingleConnectionInterface;
  12. /**
  13. * Base exception class for network-related errors.
  14. *
  15. * @author Daniele Alessandri <suppakilla@gmail.com>
  16. */
  17. abstract class CommunicationException extends PredisException
  18. {
  19. private $connection;
  20. /**
  21. * @param SingleConnectionInterface $connection Connection that generated the exception.
  22. * @param string $message Error message.
  23. * @param int $code Error code.
  24. * @param \Exception $innerException Inner exception for wrapping the original error.
  25. */
  26. public function __construct(
  27. SingleConnectionInterface $connection,
  28. $message = null,
  29. $code = null,
  30. \Exception $innerException = null
  31. ) {
  32. parent::__construct($message, $code, $innerException);
  33. $this->connection = $connection;
  34. }
  35. /**
  36. * Gets the connection that generated the exception.
  37. *
  38. * @return SingleConnectionInterface
  39. */
  40. public function getConnection()
  41. {
  42. return $this->connection;
  43. }
  44. /**
  45. * Indicates if the receiver should reset the underlying connection.
  46. *
  47. * @return Boolean
  48. */
  49. public function shouldResetConnection()
  50. {
  51. return true;
  52. }
  53. /**
  54. * Helper method to handle exceptions generated by a connection object.
  55. *
  56. * @param CommunicationException $exception Exception.
  57. */
  58. public static function handle(CommunicationException $exception)
  59. {
  60. if ($exception->shouldResetConnection()) {
  61. $connection = $exception->getConnection();
  62. if ($connection->isConnected()) {
  63. $connection->disconnect();
  64. }
  65. }
  66. throw $exception;
  67. }
  68. }