laravel如何捕获Throwable错误不让脚本停止

在单文件脚本中执行 可以捕获到错误 脚本不会停止

test.php文件内容

<?php
while (true){
    try {
        //直接执行未定义函数
        sdfs();
    }catch (Throwable $e) {
        echo  $e->getLine() . $e->getMessage();
    } catch (\Exception $e) {
        echo  $e->getLine() . $e->getMessage();
    } catch (Error $e) {
        echo  $e->getLine() . $e->getMessage();
    } finally {

    }
    sleep(3);
}

直接执行 php test.php

在laravel6.20框架 Command中执行 会导致脚本停止

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TestCommand extends Command
{
    protected $signature = 'test';
    protected $description = 'Command description';
    public function __construct()
    {
        parent::__construct();
    }
    public function handle()
    {
        while (true){
            try {
                //直接执行未定义函数
                sdfs();
            }catch (Throwable $e) {
                //
                echo  $e->getLine() . $e->getMessage();
            } catch (\Exception $e) {
                echo  $e->getLine() . $e->getMessage();
            } catch (Error $e) {
                echo  $e->getLine() . $e->getMessage();
            } finally {

            }
            sleep(3);
        }
    }
}
  • 以上执行 php artisan test 会抛出错误并中断脚本
    Symfony\Component\Debug\Exception\FatalThrowableError : Call to undefined function App\Console\Commands\sdfs()
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

catch throwable 然后继续执行你下面的逻辑 或者停止 不过在command内 会直接抛出 因为comman内没有exception handle的行为 你可以自己捕捉

4年前 评论
讨论数量: 3

尝试 catch FatalThrowableError

4年前 评论
discoverer (楼主) 4年前

catch throwable 然后继续执行你下面的逻辑 或者停止 不过在command内 会直接抛出 因为comman内没有exception handle的行为 你可以自己捕捉

4年前 评论
use Throwable;

or

try{
}catch(\Theowable $e){
}

image

建议学习下语法或者使用phpstorm编程!

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!