1

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.
donquixote
  • 4,877
  • 3
  • 31
  • 54

1 Answers1

2

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 
}
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
  • Ok! In addition, maybe it is a good idea to have a common base class that allows an array of previous exceptions? – donquixote Feb 23 '16 at 18:20
  • And if calling code does not bother to catch, and I simply want the command line to "handle" the exceptions by printing the stack trace? (E.g. while fooling around with new code). I think the cli does print the stack trace of the "previous" exception, but it won't understand that there can be additional data in the unhandled exceptions.. – donquixote Feb 23 '16 at 18:22
  • 1
    Printing a chain of exceptions is a trivial recursion. Printing a tree of exceptions is a bit more tricky and will be much less readable. – Alex Blex Feb 23 '16 at 21:38
  • @AlexBlex adding to your point, I think the crux of this question is about displaying said exceptions. Storing multiple exceptions (or any other data) is the "easy part". – Christian Aug 08 '22 at 17:22
  • @Christian, Frankly I can't recall what was the problem back in 2016, but 6 years later, "displaying" is trivial - `echo $e` prints out the whole chain: https://onlinephp.io/c/f9141 – Alex Blex Aug 09 '22 at 22:51