Search code examples
phprabbitmqamqp

Is catching an exception and continuing program execution a best practice?


My app connects to rabbitMQ. Sometimes, it's throwing an AMQPTimeoutException. More specifically "Error sending data. Socket connection timed out."

My solution:

I'm catching the AMQPTimeoutException and calling my reconnect method. After which the program continues it's normal execution. Also I've set a flag so that the exception is handled atmost 3 times.

try
{
    sendMethod($message);
} catch (AMQPTimeoutException $e) {
      echo "caught socket connection exception". "\n";
      $this->reconnect($message, $exchangeName, $queue);
  }
//reconnect internally checks the flag

My question : Is this a best practice? If not what other solutions are possible?

Note : The app is written in PHP.


Solution

  • Yes.

    Exceptions should always be caught and handled. This is most certainly best practice. Exceptions are control flow structures in a language that allows programmers to deal with things that they did not expect to happen or very rarely expect to happen.

    In your scenario, it is perfectly reasonable to catch exceptions when it comes to Sockets. TCP/IP communication is not perfect and depending upon a wide range of conditions socket failure is 100% certain at some point in time.

    What I would recommend is that you start logging WHY these socket timeouts happen. Typically they are caused by resource exhaustion, but where is it? Server A or Server B... or that client...

    Timeouts are a symptom of a problem that needs to be investigated. While you are handling them correctly, I would strongly suggest adding some logging to find out why they are occurring.