0

我有一个在 laravel 5.0 上使用 try .. catch 和使用系统命令制作的命令应用程序代码。当出现异常时,我的捕获不起作用。

use Illuminate\Support\Facades\Log;
...
try {
  system('.dump master | sqlite3 ' . $older . ' > ' . storage_path() . '/tmp/' . $tabla . '.sql' );
} catch ( \Exception $e) {
  Log::alert('Problem import old table '. $tabla . $e->GetMessage());
}

我在 shell 上看到了我的错误,但没有写在我自己的 laravel 日志上。(日志:警报)

4

2 回答 2

2

您必须获得访问权限,STDERR并且可能,STDOUT. 使用proc_open,例如:

$desc = [
  1 => ['pipe', 'w'], // STDOUT
  2 => ['pipe', 'w'], // STDERR
];

$proc = proc_open('ls -l . something', $desc, $pipes);
if (is_resource($proc)) {

  if ($out = stream_get_contents($pipes[1])) {
    echo $out;
  }
  fclose($pipes[1]);


  if ($err = stream_get_contents($pipes[2])) {
    fprintf(STDERR, "Error: %s\n", $err);
  }
  fclose($pipes[2]);

  // You can also check the process exit status
  // 0 means success, otherwise error.
  $exit_status = proc_close($proc);
}

当然STDOUT,如果命令将其重定向到文件,则不需要管道。

是的,system()不会抛出异常。STDERR显然,您可以实现自己的类,如果进程退出状态不为零,或者管道中捕获了某些东西,它将抛出异常:

class MyShellException extends \Exception {}

class MyShell {
  public static function execute($command, &$out = null) {
    if (func_num_args() > 1) {
      $desc[1] = ['pipe', 'w'];
    } else {
      $desc[1] = ['file', '/dev/null'];
    }

    $desc[2] = ['pipe', 'w'];

    $proc = proc_open($command, $desc, $pipes);
    if (is_resource($proc)) {
      if (isset($pipes[1])) {
        $out = stream_get_contents($pipes[1]);
        fclose($pipes[1]);
      }

      if ($err = stream_get_contents($pipes[2])) {
        fclose($pipes[2]);
        throw new MyShellException("Command $command failed: $err");
      }

      if ($exit_status = proc_close($proc)) {
        throw new MyShellException("Command $command exited with non-zero status");
      }
    }
  }
}


try {
  MyShell::execute('ls -l . something', $out);
  echo "Output: $out\n";
} catch (MyShellException $e) {
  if (!empty($out)) {
    echo "Output: $out\n";
  }
  fprintf(STDERR, "MyShell error: " . $e->getMessage());
  exit(1);
}
于 2016-04-27T11:30:13.033 回答
0

在 php 中使用抛出异常。 这是要使用的参考链接和示例:

<?php
/*
 * 
 * opcode number: 108
 */
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>
于 2016-04-27T11:39:17.197 回答