好吧,我想我要在这里失去理智了......
一直在尝试和测试,但似乎无法加载自定义 HTTP 500 错误页面。 Chrome 一直为我提供默认的“此页面无效,HTTP 错误 500”错误页面。
我采取的步骤:
访问日志
:1 - - [10/Aug/2018:20:51:39 +0200] "GET / HTTP/1.1" 500 -
错误日志
[Fri Aug 10 20:51:39.156104 2018] [php7:error] [pid 11608] [client ::1:65263] PHP Fatal error: Uncaught Error: Class 'tests' not found in /private/var/www/development/public_html/index.php:7\nStack trace:\n#0 {main}\n thrown in /private/var/www/development/public_html/index.php on line 7
.htaccess 行
ErrorDocument 400 /404.php
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php
ErrorDocument 405 /405.php
ErrorDocument 408 /408.php
ErrorDocument 500 /500.php
ErrorDocument 502 /502.php
ErrorDocument 504 /504.php
Apache 2.4+
PHP 7+
我在这里没有看到这个问题,特别是因为上面的 404 版本运行完美。 500.php 只包含 echo '500';
我在这里错过了一些 Apache 设置吗?是不是因为是本地的...
最佳答案
你的评论基本上是正确的。许多 500 错误不会以 .htaccess
的方式到达 apache。将能够重定向到错误文档。
有两种方法可以为 5xx 错误发布自定义模板。您使用哪一个将取决于错误是什么。如果错误是“Catchable ”,您只需要将函数包装在 try/catch
中堵塞。像这样的东西:
try{
someUndefinedFunction();
} catch (Throwable $exception) { //Use Throwable to catch both errors and exceptions
header('HTTP/1.1 500 Internal Server Error'); //Tell the browser this is a 500 error
echo $e->getMessage();
}
请注意,在此示例中,必须手动设置 500 错误 header 。这是因为错误在
try{}
内从浏览器的角度来看,阻止服务器实际上并没有出错。如果 500 错误是由无法捕获的内容引起的,那么您需要注册自定义关闭功能。这在 php7+ 中不太常见,但仍然可能是必要的,具体取决于您在做什么。完成的方法是包含这样的内容:
function handle_fatal_error() {
$error = error_get_last();
if (is_array($error)) {
$errorCode = $error['type'] ?? 0;
$errorMsg = $error['message'] ?? '';
$file = $error['file'] ?? '';
$line = $error['line'] ?? null;
if ($errorCode > 0) {
handle_error($errorCode, $errorMessage, $file, $line);
}
}
}
function handle_error($code, $msg, $file, $line) {
echo $code . ': '. $msg . 'in ' . $file . 'on line ' . $line;
}
set_error_handler("handle_error");
register_shutdown_function('handle_fatal_error');
关于php - 自定义 apache 500 错误 PHP 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51792814/