PHP:防止嵌套的try-catch捕获特定错误

时间:2016-12-28 20:55:44

标签: php try-catch

我有一个PHP脚本需要执行回调函数并捕获特定类型的错误。

<?php

class MyException extends Exception{}

function doStuff(callable $callback){

    try{
        $callback();
    }
    catch(MyException $e){
        #Deal with it
    }
}

?>

回调函数可以使用try-catch来防止我的异常被冒泡。如何允许回调函数实现try-catch块但不允许它捕获MyException?

1 个答案:

答案 0 :(得分:0)

如果我错误地读了这个问题,请原谅我 - 我不能想到需要这样的用例 - 但我认为这样的事情会起作用:

<?php

class MyException extends Exception {}

/*
 * This method is in the library. It's not in your control
 */
function doStuff(callable $callback) {
    try {
        $callback();
    } catch(Exception $e) {
        die($e->getMessage());
    }
}

/*
 * We want to do something, but not let any MyException pass through to doStuff()
 */
doStuff(function() {
    try {
        connect('mysql:dbname=IDoNotExist;host=127.0.0.1', 'batman', 'robin');
    } catch(MyException $e) {
        return; // Do nothing with MyException, continue as if it didn't happen
    } catch(Exception $e) {
        throw new Exception($e); // Not an instance of MyException ... let the library handle it
    }
});

/*
 * This is dummy code that will throw MyException if the username and password are incorrect
 */
function connect($dsn, $username, $password) {
    try {
        $dbh = new PDO($dsn, $username, $password);
    } catch(PDOException $e) {
        throw new MyException($e->getMessage());
    }
}

我假设,通过阅读评论和您的回复,doStuff()是您传递callable的图书馆电话。如果你的回调中的代码捕获MyException,你想要完全忽略它。

上面的代码将完全忽略MyException,好像什么都没发生一样。虽然我从不提倡这样的解决方案。