php - 当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 但没有任何效果。任何帮助表示赞赏。
解决方案
如果您查看本手册,您会看到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
}
额外建议(不在问题范围内):
没有以重复方式检查文件是否存在的逻辑。
如果文件已下载,它将存在,否则您将永远不会在递归期间下载它。
如果有人将链接传递给不存在的文件怎么办?
最好下载它并停止成功或异常。
推荐阅读
- javascript - 从 var js 获取特定的 tagName
- jquery - ngx-datatable 汇总行不适用于列属性中的 summaryFunc。此外,所有汇总值都连接为字符串
- c - 在 MIPS TLB 中,虚拟地址和物理地址之间的混淆
- c# - Timeinterval 在应用程序运行时每 3 分钟检查一次后端是否存在数据库连接 C#
- angularjs - 在 onInit 函数中访问 transclude 槽
- python - 使用日期将 Pandas 数据框合并到多索引
- c++ - 如何在c++中将分数转换为浮点数
- wpf - 向 WPF DecExpress 网格中的单元格添加图标
- linux - 运行 python 脚本时出现问题,该脚本依赖于来自终端的其他文件?
- python - python linux debain的openAi健身房