trap gd-webp cannot allocate temporary buffer error in PHP 8 when using imagecreatefromstring

one text

It appears you get gd-webp cannot allocate temporary buffer error error when loading an animated WebP image via imagecreatefromstring gd function

How do you trap this error? I tried it like this but the error throws anyway:

try {
    
    // ...
    $resource = @imagecreatefromstring($binary);

} catch (Throwable $exception) {
    
    // Handle the error

}

So I went for a low-tech solution, which appears to get the job done - is there a better way to do this?

try {
    
    // ...
    if (isAnimatedWebP($imageUrl)) {
        throw new Exception('Unsupported');
    }

    // ...
    $resource = @imagecreatefromstring($binary);

} catch (Throwable $exception) {
    
    // Handle the error

}

function isAnimatedWebP(string $imageUrl): bool
{
    $fileData = file_get_contents($imageUrl, false, NULL, 0, 40);
    if (
        stripos($fileData, 'WEBPVP8X') !== false ||
        stripos($fileData, 'ANIM') !== false
    ) {
        return true;
    }
    return false;
}

Source