Created
February 15, 2020 06:10
-
-
Save sshymko/0bc2ea1a2f3b23c6c5f7952492a51acd to your computer and use it in GitHub Desktop.
Chaining of immutable throwable exceptions/errors (PHP8 proposal)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface Throwable | |
{ | |
/** | |
* Return immutable copy with causal chain extended by given root cause | |
* | |
* @return Throwable | |
*/ | |
public function chain(Throwable $cause = null): Throwable; | |
} | |
class Exception implements Throwable | |
{ | |
public function chain(Throwable $cause = null): Throwable | |
{ | |
// Return immutable self with already matching causal chain | |
if (!$cause) { | |
return $this; | |
} | |
// Create immutable copy of causal chain extended by given root cause | |
$prev = $this->getPrevious() | |
? $this->getPrevious()->chain($cause) | |
: $cause; | |
// Create immutable copy of self with the extended causal chain | |
$self = clone $this; | |
$self->previous = $prev; | |
return $self; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use Case
Re-throwing multiple exceptions aggregated during graceful fallback that eventually fails.
Exceptions are chained in order of occurrence carrying informative history of execution: