LoginSignup
20
24

More than 5 years have passed since last update.

PHPのエラーを補足して例外に変換する

Posted at

はじめに

PHPのエラーを補足して例外に変換する方法を記述します。

環境

  • CentOS 6.5
  • PHP 5.3.3

PHPのエラーを例外に変換する

エラーハンドラを利用しない場合

$ php -r 'fopen("/var/log/messages", "r");'
PHP Warning:  fopen(/var/log/messages): failed to open stream: Permission denied in Command line code on line 1

エラーハンドラでエラーを例外に変換する

sample_error_handler.php
<?php

// エラーハンドラを登録する
set_error_handler(
  function ($errno, $errstr, $errfile, $errline) {
    // エラーが発生した場合、ErrorExceptionを発生させる
    throw new ErrorException(
      $errstr, 0, $errno, $errfile, $errline
    );
  }
);

function main($filename) {
  try {
    // execute関数の呼び出し
    execute($filename);
  } catch (Exception $e) {
    // エラーの原因を出力
    $previous = $e->getPrevious();
    printf("%s %s(%d)\n", $e->getMessage(), $e->getFile(), $e->getLine());
    printf("# %s %s(%d)\n", $previous->getMessage(), $previous->getFile(), $previous->getLine());
  }
}

function execute($filename) {
  $handle = null;
  try {
    $handle = fopen($filename, "r");
    while (! feof($handle) ) {
      $line = fgets($handle);
      echo "$line";
    }
  } catch (ErrorException $e) {
    if ( ! is_null($handle) ) {
      fclose($handle);
    }
    // ErrorExceptionを補足して、新たにExceptionをスローする
    throw new Exception("failed to open file filename:[$filename]", $e->getCode(), $e);
  }
}

コマンドライン引数をmain関数の引数として呼び出し
main($argv[1]);

?>
  • 動作確認

エラーなしの場合

$ php sample_error_handler.php /etc/hosts
127.0.0.1               localhost.localdomain localhost
::1             localhost6.localdomain6 localhost6

エラーが発生する場合

$ php sample_error_handler.php /var/log/messages
failed to open file filename:[/var/log/messages] /path/to/sample_error_handler.php(33)
# fopen(/var/log/messages): failed to open stream: Permission denied /path/to/sample_error_handler.php(24)

参考

20
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
24