如何在 catch 块中使用 try 块中的变量

How to use a variable from a try block into the catch block

我有这个代码:

    try {
        // Get a response from an API
        $apiBody = $this->api->get('Info')
            ->getBody();
    } catch (\Exception $e) {
        if ($e instanceof ConnectException) {
            // Set a flash error message
            $this->session->getFlashBag()->add('danger', 'Errore durante l\'importazione. URL non valido.');
            $wrongUrlNotification = new Notification();
            $wrongUrlNotification->setForUser($user)
                ->setMessage('Errore durante l\'importazione. URL non valido.');
            $this->em->persist($wrongUrlNotification);
        } else {
            // Set a flash error message
            $message = 'Errore durante l\'importazione. Il messaggio restituito dal sistema è il seguente: ' . $e->getMessage() . ' [CODICE: ' . $e->getCode() . ']';
            $this->session->getFlashBag()->add('danger', $message);
            $exceptionNotification = new Notification();
            $exceptionNotification->setForUser($user)
                ->setCreatedOn(new \DateTime())
                ->setCode(0)
                ->setMessage($message)
                ->setDebug($apiBody);
            $this->em->persist($exceptionNotification);
        }
    }

问题出在变量 $apiBody 上。

如您所见,我在 try 块中给它赋值。如果抛出异常,我想将 API 返回的字符串存储在数据库中,以便稍后调试它并了解导致错误的原因。

问题是 PHPStorm 告诉我 catch 块中的 $apiBody 未定义,而且在数据库中它存储为 null 值。

我不明白为什么...我从来没有处理过这种情况,但我认为变量是定义的。

我错过了什么?如果触发异常,如何将 API 的响应主体存储在数据库中?

$this->api->get('Info')->getBody() 的某处抛出了异常。它甚至没有得到 return 个值,更不用说将该值分配给 $apiBody。变量确实没有定义,因为在定义它的过程中抛出了异常