如何在PHP中捕获require()或include()的错误? [英] How to catch error of require() or include() in PHP?

查看:1182
本文介绍了如何在PHP中捕获require()或include()的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PHP5中编写一个需要某些文件的代码的脚本。当文件不可用于包含时,首先发出警告,然后抛出致命错误。我想打印一个自己的错误信息,当不可能包含代码。如果请求不起作用,是否可以执行最后一个命令?以下内容不起作用:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆