解决 Laravel 执行 Shell 命令不抛异常

PHP 投稿 61400 0 评论

解决 Laravel 执行 Shell 命令不抛异常

exec() 和 shell_exec() 都能执行 shell 命令。

shell_exec() 和 exec() 不会抛出异常,不知道因为什么原因而崩溃,他们只是默默地执行失败了,因此不好进行错误定位。

解决Laravel执行Shell命令不抛异常的方案:

use Symfony\Component\Process\Process;
class ShellCommand
{
    public static function execute($cmd): string
    {
        $process = Process::fromShellCommandline($cmd);
        $processOutput = '';
        $captureOutput = function ($type, $line) use (&$processOutput) {
            $processOutput .= $line;
        };
        $process->setTimeout(null)->run($captureOutput);
        if ($process->getExitCode()) {
            $exception = new ShellCommandFailedException($cmd . " - " . $processOutput);
            report($exception);
            throw $exception;
        }
        return $processOutput;
    }
}

它使用了 Symfony 的 Process 组件。 

使用这种方法,就可以抛出一个自定义异常,记录命令和输出,或者是记录到日志以寻找问题。

编程笔记 » 解决 Laravel 执行 Shell 命令不抛异常

赞同 (51) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽