如何在PHP中捕获require()或include()的错误? [英] How to catch error of require() or include() in PHP?
问题描述
require('fileERROR.php5')或死(无法加载配置文件) ;
使用 error_reporting(0)
只给出一个白色的屏幕,不使用error_reporting给出了我不想显示的PHP错误。
您可以使用 set_error_handler
结合 ErrorException
。
来自 ErrorException
页面的示例是:
<?php
函数exception_error_handler($ errno,$ errstr,$ errfile,$ errline){
throw new ErrorException $ errstr,$ errno,0,$ errfile,$ errline);
}
set_error_handler(exception_error_handler);
/ *触发器异常* /
strpos();
?>
一旦您将错误作为例外处理,您可以执行以下操作:
<?php
try {
include'fileERROR.php5';
} catch(ErrorException $ ex){
echo无法加载配置文件。
//如果你愿意,你可以退出或死在这里 - 你也可以记录你的错误,
//或你想要的任何其他步骤
}
?>
I'm writing a script in PHP5 that requires the code of certain files. When A file is not available for inclusion, first a warning and then a fatal error are thrown. I'd like to print an own error message, when it was not possible to include the code. Is it possible to execute one last command, if requeire did not work? the following did not work:
require('fileERROR.php5') or die("Unable to load configuration file.");
Supressing all error messages using error_reporting(0)
only gives a white screen, not using error_reporting gives the PHP-Errors, which I don't want to show.
You can accomplish this by using set_error_handler
in conjunction with ErrorException
.
The example from the ErrorException
page is:
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
/* Trigger exception */
strpos();
?>
Once you have errors being handled as exceptions you can do something like:
<?php
try {
include 'fileERROR.php5';
} catch (ErrorException $ex) {
echo "Unable to load configuration file.";
// you can exit or die here if you prefer - also you can log your error,
// or any other steps you wish to take
}
?>
这篇关于如何在PHP中捕获require()或include()的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!