LoginSignup
12
12

More than 5 years have passed since last update.

PHP 5.2/5.3 にて組み込み関数をtry catch対応にする方法

Last updated at Posted at 2014-12-03

エラーが予期せずレスポンスに混ざったり、エラーが発生していたかどうかをその都度if文で判定していたら、コードが汚くなってしまいます。
そこで、組み込み関数のエラーを全て例外として投げ、適切に扱えるようにするためのコードを紹介します。

PHP 5.3 未満で使える実装

PHP 5.3より前のバージョン、例えばPHP 5.2などで使う際は次の実装を使います。

set_error_handler(
    create_function(
      '$severity, $message, $file, $line',
      'throw new ErrorException($message, 0, $severity, $file, $line);'
    )
);

PHP 5.3 以降で使える実装

PHP5.3.0から使えるようになった無名関数を使った実装です。

set_error_handler(function($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
});

利用例

次のような実装をすると、組み込み関数からも例外エラーが投げられるようになります。

<?php
class ExampleClass
{
    static public function main()
    {
        self::setErrorHandler();
        try {
            self::getContent();
        } catch (ErrorException $e) {
            // 例外となります
            echo 'Error: ' . $e->getMessage();
        }
    }

    static private function getContent()
    {
        file_get_contents("http://not-exists-domain.com");
    }

    static private function setErrorHandler()
    {
        // 上記のPHP 5.3未満でも動く実装を入れております
        set_error_handler(
            create_function(
              '$severity, $message, $file, $line',
              'throw new ErrorException($message, 0, $severity, $file, $line);'
            )
        );
    }
}

ExampleClass::main();

組み込み関数標準のエラー出力ではこういった出力でした。

PHP Warning:  file_get_contents(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in /tmp/exception_test.php on line 16
PHP Warning:  file_get_contents(http://not-exists-domain.com): failed to open stream: php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known in /tmp/exception_test.php on line 16

今回の実装で例外エラー化すると、次のような出力を得られます。

Error: file_get_contents(): php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known

参考

12
12
1

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
12
12