Why isn't try catch exception block not handling 504 Gateway Timeout

30% of the time, my response via a AJAX call is returning 504 Gateway Timeout.
But I can’t seem to ‘catch’ it as an exception.

    try
    {
        $response = $client->chat()->create([
            'model' => $model,
            'messages' => [
                ['role' => 'user', 'content' => $prompt],
            ],
            'temperature' => $temperature,
            'max_tokens' => $max_tokens,
            'top_p' => $top_p,
            'frequency_penalty' => $frequency_penalty,
            'presence_penalty' => $presence_penalty
        ]);

        $answer = trim($response['choices'][0]['message']['content']);
    }
    catch (Exception $e)
    {
        $answer = "";
    }