2016-04-27 15 views
0

私は、try .. catchとuse systemコマンドでlaravel 5.0で作成したコマンドアプリのコードを用意しています。例外があると、私のキャッチは機能しません。try .. laravel 5.0のsystem()コマンドphpでキャッチしてください。

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()); 
} 

シェルでエラーが表示されますが、自分のlaravelログには書き込まれません。 (ログ:アラート)

+0

外部/システムコールは、それ自体が例外を生成しません。 – mario

+0

'' .dump master'? '$ PATH'で実行可能な' .dump'を検索するか、現在の作業ディレクトリにある 'dump'を実行する' ./dump master'を使用しますか?とにかく絶対パスを構築することをお勧めします。たとえば、 '$ cmd = __DIR__。 '/../somewhere/dump master''または '$ cmd = YOUR_ROOT_DIR。 '/ bin/dump master'' –

+0

私はエラーについては確信していません。私はtry..catchについて語る。私はそれが何か誤りであることを知っている。 – abkrim

答えて

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()は例外をスローしません。

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); 
} 
0

PHPで利用スロー例外:もちろん、あなたは、プロセスの終了ステータスがゼロでない、またはSTDERRパイプに巻き込ま何かがあるかどうかの場合には例外がスローされます独自のクラスを実装することができます。使用する Here is the reference linkとサンプル例:

<?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'; 
?> 
関連する問題