R_U*_*ser 16 php error-handling try-catch require fatal-error
我正在用PHP5编写一个需要某些文件代码的脚本.当A文件不可用时,首先会发出警告,然后抛出致命错误.当无法包含代码时,我想打印自己的错误消息.如果requeire不起作用,是否可以执行最后一个命令?以下不起作用:
require('fileERROR.php5') or die("Unable to load configuration file.");
Run Code Online (Sandbox Code Playgroud)
error_reporting(0)仅使用白色屏幕来抑制所有错误消息,而不是使用error_reporting给出PHP错误,我不想显示它.
Sja*_*son 17
您可以通过set_error_handler结合使用来实现此目的ErrorException.
该ErrorException页面的示例是:
<?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();
?>
Run Code Online (Sandbox Code Playgroud)
一旦您将错误作为例外处理,您可以执行以下操作:
<?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
}
?>
Run Code Online (Sandbox Code Playgroud)
小智 15
我只使用'file_exists()':
if (file_exists("must_have.php")) {
require "must_have.php";
}
else {
echo "Please try back in five minutes...\n";
}
Run Code Online (Sandbox Code Playgroud)
更好的方法是首先在路径上使用realpath.如果文件不存在,realpath将返回false.
$filename = realpath(getcwd() . "/fileERROR.php5");
$filename && return require($filename);
trigger_error("Could not find file {$filename}", E_USER_ERROR);
Run Code Online (Sandbox Code Playgroud)
您甚至可以在应用程序的命名空间中创建自己的require函数,该函数包含PHP的require函数
namespace app;
function require_safe($filename) {
$path = realpath(getcwd() . $filename);
$path && return require($path);
trigger_error("Could not find file {$path}", E_USER_ERROR);
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以在文件中的任何位置使用它
namespace app;
require_safe("fileERROR.php5");
Run Code Online (Sandbox Code Playgroud)
我建议您查看set_error_handler()函数文档中的最新评论。
它建议将以下内容作为捕获致命错误的方法(并带有示例):
<?php
function shutdown()
{
$a=error_get_last();
if($a==null)
echo "No errors";
else
print_r($a);
}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);
?>
Run Code Online (Sandbox Code Playgroud)
我还没有尝试过这个建议,但这可能可以用于其他致命错误场景。