无法使用 ...catch( \Exception $e ){... in PHP/Lumen 8.x 捕获异常

Can't catch exceptions with ...catch( \Exception $e ){... in PHP/Lumen 8.x

我正在开发一个 PHP/Lumen 8.x foreach 循环来管理来自 mysql 数据库 table 的 update/insert 记录,我在其中我试图捕获 update/insert 过程中的任何错误,以便在出现错误时可以继续处理后续日志。因为我在 Lumen 中,并且我们在 catch 语句中处于某个命名空间环境中,所以我使用“\Exception”来标识异常类型。但是,在发生错误的任何情况下,我都无法捕获它,并且在控制器输出中,即在控制器响应中,将触发指示“检测到递归”的错误。我也无法捕获最后一个错误。

这是 foreach(...) { ... try..catch ...} 块的代码片段:

foreach($prdsData as $prod){

    $cr_sku = $prod['SKU'];

    try{

        $res_prod_uc[$cr_sku]['err'] = false;

        $res_prod_uc[$cr_sku]['res'] = wc_product_update($pd);

    } catch( \Exception $e ){

        $res_prod_uc[$cr_sku]['err'] = true;

        $cr_err_dt = array(
                        'code'  => $e->getCode(),
                        'msg'   => $e->getMessage(),
                        'file'  => $e->getFile(),
                        'line'  => $e->getLine(),
                        'trace' => $e->getTrace()
                    );

        $res_prod_uc[$cr_sku]['err_data'] = $cr_err_dt;

        continue;
    }
}

return response()->json($res_prod_uc,200); // this is where the "Recursion detected" error is triggered

这是“检测到递归”错误的输出 (JSON):

{
    "message": "Recursion detected",
    "exception": "InvalidArgumentException",
    "file": "..../blog/vendor/illuminate/http/JsonResponse.php",
    "line": 88,
    "trace": [
        {
            "file": "..../blog/vendor/symfony/http-foundation/JsonResponse.php",
            "line": 54,
            "function": "setData",
            "class": "Illuminate\Http\JsonResponse",
            "type": "->"
        },
        {
            "file": "..../blog/vendor/illuminate/http/JsonResponse.php",
            "line": 32,
            "function": "__construct",
            "class": "Symfony\Component\HttpFoundation\JsonResponse",
            "type": "->"
        },
        {
            "file": "..../blog/vendor/laravel/lumen-framework/src/Http/ResponseFactory.php",
            "line": 40,
            "function": "__construct",
            "class": "Illuminate\Http\JsonResponse",
            "type": "->"
        },
        
        /* this is my controller */
        {
            "file": "..../blog/app/Http/Controllers/ProductsController.php", 
            "line": 145,
            "function": "json",
            "class": "Laravel\Lumen\Http\ResponseFactory",
            "type": "->"
        },....

我怎样才能捕捉到任何错误?

提前致谢

发生的事情正是你所说的@aynber。我确实检查过,是的,正在缓存异常,但是 'trace' => $e->getTraceAsString() 行确实在更深层次上有对象递归的地方分配了数据。当线程到达 return response()->json($res,200); (在 try..catch 块之外)时,会引发“检测到递归”错误。此错误是由调用 Lumen 8 框架中的 json_encode() PHP 函数生成的。

我使用的解决方案是将 getTrace() 方法替换为 getTraceAsString() Exception 对象方法。