php – 如何在其他try catch块中处理异常?

我的例子:

class CustomException extends \Exception {

}

class FirstClass {
    function method() {
        try {
            $get = external();
            if (!isset($get['ok'])) {
                throw new CustomException;
            }

            return $get;
        } catch (Exception $ex) {
            echo 'ERROR1'; die();
        }
    }
}

class SecondClass {
    function get() {
        try {
            $firstClass = new FirstClass();
            $get = $firstClass->method();
        } catch (CustomException $e) {
            echo 'ERROR2'; die();
        }
    }
}

$secondClass = new SecondClass();
$secondClass->get();

这让我回复“ERROR1”,但我想从SecondClass收到“ERROR2”.

在FirstClass块中,try catch应该处理来自external()方法错误.

我该怎么做?

解决方法:

您应该抛出另一个异常并注册一个全局异常处理程序,而不是打印错误消息并终止整个PHP进程,该异常处理程序对未处理的异常进行异常处理.

class CustomException extends \Exception {

}

class FirstClass {
    function method() {
        try {
            $get = external();
            if (!isset($get['ok'])) {
                throw new CustomException;
            }

            return $get;
        } catch (Exception $ex) {
            // maybe do some cleanups..
            throw $ex;
        }
    }
}

class SecondClass {
    function get() {
        try {
            $firstClass = new FirstClass();
            $get = $firstClass->method();
        } catch (CustomException $e) {
            // some other cleanups
            throw $e;
        }
    }
}

$secondClass = new SecondClass();
$secondClass->get();

您可以使用set_exception_handler注册一个全局异常处理程序

set_exception_handler(function ($exception) {
    echo "Uncaught exception: " , $exception->getMessage(), "\n";
});

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...