エラーが予期せずレスポンスに混ざったり、エラーが発生していたかどうかをその都度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
参考
-
PHP - set_error_handler と ErrorException を組み合わせると幸せになるかも - Qiita
http://qiita.com/suin/items/14c455691a0391ee265c -
How can I handle the warning of file_get_contents() function in PHP? - Stack Overflow
http://stackoverflow.com/questions/272361/how-can-i-handle-the-warning-of-file-get-contents-function-in-php -
PHPの組み込み関数で例外を発生させる方法 | 徳丸浩の日記
http://blog.tokumaru.org/2012/04/raising-exceptions-with-built-in-php.html