【问题标题】:multiple methods try without skipping others php多种方法尝试不跳过其他php
【发布时间】:2019-02-21 08:13:52
【问题描述】:

我有这个代码:

try{
  firstMethod()
  secondMethod()
}
catch(Exception $e){
  ....
}

我想要的是执行所有 try/catch 块函数,但如果有一个抛出异常则捕获,而不跳过以下方法 一个可能但不漂亮的代码是:

try{
  firstMethod();
}
catch(Exception $e){
  ....
}
try{
  secondMethod();
}
catch(Exception $e){
  ....
}

【问题讨论】:

  • 无法理解。您的问题是什么?
  • 尝试{ firstMethod(); secondMethod();} catch(Exception $e){} ...这有什么问题?

标签: php exception try-catch


【解决方案1】:

如果您正在寻找比“不漂亮”更方便的方法,我假设您可能有 很多

我会说只是循环遍历它们:

foreach ( [ 'firstMethod', 'secondMethod' ] as $callable ) {
    try {
        $callable();
    }
    catch ( Exception $e ) {

    }
}

【讨论】:

  • 这很好。我没有想到这一点。如果方法需要不同的变量,这将是有问题的,但否则,非常好。
  • 这可以针对更复杂的用例分别进行扩展,例如你可以有一个工厂为集合生成闭包回调。
【解决方案2】:

为什么不在每个函数中编写 try catch 并在某处记录异常。

function firstMethod() {
    try {
        //code
    }
    catch (Exception $e) {
        logException($e);
    }
}

function secondMethod() {
    try {
        //code
    }
    catch (Exception $e) {
        logException($e);
    }
}

function mainMethod() {
    firstMethod();
    secondMethod();
}

这将有助于做这样的事情:

function someOtherMethod() {
    secondMethod();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2020-09-22
    • 2015-06-29
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    相关资源
    最近更新 更多