Search code examples
phpexceptiontry-catchrethrow

PHP: Throw exception with multiple original/previous exceptions?


Consider the following code, where I want to throw a new exception to wrap "previous" exceptions that I just caught.

try {
  doSomething();
}
catch (SomethingException $eSomething) {
  try {
    rollback();
  }
  catch (RollbackException $eRollback) {
    throw new SomethingRollbackException('Copying failed, rollback failed.', null, $eSomething, $eRollback);
  }
}

At some point I have two exceptions that I would want to pass in as "$previous", when constructing a new exception.

But natively, only one "previous exception" is supported.

Options I can think of so far:

  • Create my own exception class that accepts an additional "previous" exception. But then what? Store it as a private property? Or public? With an accessor? How would I make calling code to care about the extra information?
  • Of course I could just write to the log, and discard one or both of the exceptions. But this is not the point of this question.

Solution

  • Create my own exception class that accepts an additional "previous" exception. - Yes, let's say SomethingRollbackException

    Store it as a private property? - Yes, but is matter of taste

    With an accessor? - Yes, see above

    How would I make calling code to care about the extra information? - something like this:

    if ($exception instanceof SomethingRollbackException) {
        // at this point you know $exception has 2 previous exceptions
    }
    

    or

    try {
        // ....
    } catch(SomethingRollbackException $e) {
        // at this point you know $exception has 2 previous exceptions 
    }