CommunicationException.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. public static function handle(CommunicationException $exception)
  60. {
  61. if ($exception->shouldResetConnection()) {
  62. $connection = $exception->getConnection();
  63. if ($connection->isConnected()) {
  64. $connection->disconnect();
  65. }
  66. }
  67. throw $exception;
  68. }
  69. }