An Interest In:
Web News this Week
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
November 17, 2021 09:45 pm GMT
Original Link: https://dev.to/kodeas/executing-shell-commands-in-laravel-1098
Executing Shell Commands In Laravel
Both shell_exec()
and exec()
do the job - until they don't.
If your command crash for some reason, you won't know - shell_exec()
and exec()
don't throw Exceptions. They just fail silently.
So, here is my solution to encounter this problem:
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; }}
It utilises Symfony's Process (which comes out of the box to Laravel).
With this way, I can throw a custom exception, log the command and the output to investigate, report it to my logs to investigate, etc.
No more failing silently
Hope you like this little piece! If you do, please give it a
Original Link: https://dev.to/kodeas/executing-shell-commands-in-laravel-1098
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To