Last active
May 11, 2019 02:23
-
-
Save uzulla/7896222 to your computer and use it in GitHub Desktop.
PHPでいいかんじにエラーをあつかうの巻
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// いらんものを画面にだされては困るので | |
ini_set("display_errors", 0); | |
ini_set("display_startup_errors", 0); | |
// NoticeやDeprecated含めて全部のエラーがほしい | |
error_reporting(E_ALL); | |
// ログファイル設定はmod_phpやBuiltin Serverなどでは設定不要、 | |
// 設定しないとSTDERRに出力される | |
// ini_set("log_errors", 1); | |
// ini_set("error_log", "php-error.log"); | |
// プログラム終了時に一律でコールされるregister_shutdown_functionにコールバックを登録 | |
// error_get_last()返値を見て、「重大なのエラーなら」処理する | |
// 重大なエラーでなければ、以後の例外変換が動くはず。 | |
// これがないと、致命的なエラーでは「白い画面」が出る。 | |
// チェックするエラーはお好きなのをif文に追加しよう!!! | |
register_shutdown_function( | |
function(){ | |
$e = error_get_last(); | |
if( $e['type'] == E_ERROR || | |
$e['type'] == E_PARSE || | |
$e['type'] == E_CORE_ERROR || | |
$e['type'] == E_COMPILE_ERROR || | |
$e['type'] == E_USER_ERROR ){ | |
// お好きな処理を書く | |
echo "致命的なエラーが発生しました。\n"; | |
echo "Error type:\t {$e['type']}\n"; | |
echo "Error message:\t {$e['message']}\n"; | |
echo "Error file:\t {$e['file']}\n"; | |
echo "Error line:\t {$e['line']}\n"; | |
} | |
} | |
); | |
// エラー時に例外をスローするようにコールバック関数を登録 | |
set_error_handler(function($errno, $errstr, $errfile, $errline){ | |
throw new ErrorException($errstr, $errno, 0, $errfile, $errline); | |
}); | |
// 試して見る | |
try{ | |
// 関数のエラー、例外になります | |
$name = file_get_contents('not found file'); | |
// 存在しないasdf()関数をコールしてエラー。 | |
// 例外にできませんが、コードは終了されるので、 | |
// register_shutdown_functionに登録した関数がコールされます | |
asdf(); | |
}catch(Exception $e){ | |
echo "例外エラーが発生しました\n"; | |
echo $e->getLine()."\n"; | |
echo $e->getFile()."\n"; | |
echo $e->getMessage()."\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment