PHP:抛出有多个 original/previous 异常的异常?
PHP: Throw exception with multiple original/previous exceptions?
考虑以下代码,我想在其中抛出一个新异常来包装我刚刚捕获的 "previous" 个异常。
try {
doSomething();
}
catch (SomethingException $eSomething) {
try {
rollback();
}
catch (RollbackException $eRollback) {
throw new SomethingRollbackException('Copying failed, rollback failed.', null, $eSomething, $eRollback);
}
}
在某些时候,我有两个例外,我想在构建新例外时将其作为“$previous”传递。
但原生只支持一个"previous exception"。
目前我能想到的选项:
- 创建我自己的例外 class 接受额外的 "previous" 例外。但是然后呢?将其存储为私有 属性?还是public?带访问器?我如何让调用代码关心额外的信息?
- 当然我可以只写入日志,并丢弃一个或两个异常。但这不是本题的重点
创建我自己的例外 class 接受额外的 "previous" 例外。 - 是的,假设 SomethingRollbackException
将其存储为私有 属性? - 是的,但这取决于品味
有访问器吗? - 是的,见上文
如何让调用代码关心额外信息? - 像这样:
if ($exception instanceof SomethingRollbackException) {
// at this point you know $exception has 2 previous exceptions
}
或
try {
// ....
} catch(SomethingRollbackException $e) {
// at this point you know $exception has 2 previous exceptions
}
考虑以下代码,我想在其中抛出一个新异常来包装我刚刚捕获的 "previous" 个异常。
try {
doSomething();
}
catch (SomethingException $eSomething) {
try {
rollback();
}
catch (RollbackException $eRollback) {
throw new SomethingRollbackException('Copying failed, rollback failed.', null, $eSomething, $eRollback);
}
}
在某些时候,我有两个例外,我想在构建新例外时将其作为“$previous”传递。
但原生只支持一个"previous exception"。
目前我能想到的选项:
- 创建我自己的例外 class 接受额外的 "previous" 例外。但是然后呢?将其存储为私有 属性?还是public?带访问器?我如何让调用代码关心额外的信息?
- 当然我可以只写入日志,并丢弃一个或两个异常。但这不是本题的重点
创建我自己的例外 class 接受额外的 "previous" 例外。 - 是的,假设 SomethingRollbackException
将其存储为私有 属性? - 是的,但这取决于品味
有访问器吗? - 是的,见上文
如何让调用代码关心额外信息? - 像这样:
if ($exception instanceof SomethingRollbackException) {
// at this point you know $exception has 2 previous exceptions
}
或
try {
// ....
} catch(SomethingRollbackException $e) {
// at this point you know $exception has 2 previous exceptions
}