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

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

问题描述

我正在用 PHP5 编写一个需要某些文件代码的脚本.当 A 文件不可用于包含时,首先会引发警告,然后会引发致命错误.当无法包含代码时,我想打印自己的错误消息.如果 requeire 不起作用,是否可以执行最后一个命令?以下方法无效:

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.");

使用 error_reporting(0) 抑制所有错误消息只会产生白屏,不使用 error_reporting 会产生 PHP 错误,我不想显示.

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.

推荐答案

您可以使用 set_error_handlerErrorException.

You can accomplish this by using set_error_handler in conjunction with 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();
?>

一旦您将错误作为异常处理,您可以执行以下操作:

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天全站免登陆