首页 > 解决方案 > 当laravel中存在文件异常时,无法执行catch块内的代码

问题描述

当出现文件异常时,我无法在 catch 块内执行代码。下面是代码。

try {

        // Check for file size. which will make sure file exists in local server.
        filesize($localPath);
        return 'success';
    }catch(FileException $e) {

        Log::error('Error reading file size ' . $e->getMessage());
        $failedAttempts = $failedAttempts + 1;

        // Set to sleep for 10.
        sleep(10);

        // Start recursive call.
        $this->downloadMedia($url, $localPath, $failedAttempts);
    }

我也尝试了 \Exception 和 \ErrorException 但没有任何效果。任何帮助表示赞赏。

标签: phplaravellaravel-5.7

解决方案


如果您查看本手册,您会看到filesize方法不会引发异常。

返回文件的大小(以字节为单位)或 FALSE

(并在发生错误时生成 E_WARNING 级别的错误)。

并且因为看起来你没有启用错误报告或display_error指令 - 你没有看到E_WARNING

您可以手动抛出异常:

try {

    // Check for file existence or throw exception.
    if (!is_file($localPath)) {
      throw new Exception($localPath.' does not exists');
    }
    return 'success';
}
catch(Exception $e) {

 // here goes exception handling
}

额外建议(不在问题范围内)

没有以重复方式检查文件是否存在的逻辑。

如果文件已下载,它将存在,否则您将永远不会在递归期间下载它。

如果有人将链接传递给不存在的文件怎么办?

最好下载它并停止成功或异常。


推荐阅读