How would you refactor multiple catch blocks for a single try block when you have to catch multiple possible exceptions?

Posted 2 years ago by Ruffles

Hey there,

I am refactoring some code in my project and I still can't figure out how to deal with multiple catch statements for a single try block (in a job class).

What I mean is, I have the following code:

try { 
    // some code here interacting with Guzzle
}  catch (ClientException $clientException) {
       $this->status('failed', $clientException->getMessage());
   } catch (RequestException $requestException) {
       $this->status('failed', $requestException->getMessage());
   } catch (ConnectException $connectException) {
       $this->status('failed', $connectException->getMessage());
   } catch (ServerException $serverException) {
       $this->status('failed', $serverException->getMessage());
   } catch (Exception $exception) {
        $this->status('failed', $exception->getMessage());
  }
  • Anyone know a better way for refactoring this?
  • How do I handle multiple catch blocks like this?

Thanks!

Please sign in or create an account to participate in this conversation.