【问题标题】:custom apache 500 error PHP page自定义 apache 500 错误 PHP 页面
【发布时间】:2019-01-18 10:35:59
【问题描述】:

好吧,我想我要在这里失去理智了……

一直在尝试和测试,但似乎无法加载自定义 HTTP 500 错误页面。 Chrome 一直为我提供默认的“此页面无法正常工作,HTTP 错误 500”错误页面。

我采取的步骤:

  • 创建了 500.php 文件,它将显示我需要的自定义页面
  • 使用以下行更改了 .htaccess 文件
  • 在服务器上创建了一个文件,该文件将加载一个不存在的类,从而导致 500 错误。
  • Access_log 显示请求和 500 状态

访问日志

:1 - - [10/Aug/2018:20:51:39 +0200] "GET / HTTP/1.1" 500 -

错误日志

[2018 年 8 月 10 日星期五 20:51:39.156104] [php7:error] [pid 11608] [client ::1:65263] PHP 致命错误:未捕获的错误:在 /private/var/ 中找不到类“测试” www/development/public_html/index.php:7\n堆栈跟踪:\n#0 {main}\n 在第 7 行的 /private/var/www/development/public_html/index.php 中抛出

.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 设置吗?是不是因为是本地的...

【问题讨论】:

  • 刚刚在 SO:stackoverflow.com/questions/5765319/… 上找到了这篇文章。似乎 500 错误永远不会“到达”Apache ......所以这是否意味着我需要在我的框架中创建某种自定义错误捕获器?

标签: php apache custom-error-pages


【解决方案1】:

您的评论基本上是正确的。许多 500 错误不会以 .htaccess 能够重定向到错误文档的方式到达 apache。

您可以通过 2 种方法为 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 错误标头。这是因为由于错误位于 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');

【讨论】:

  • 是的,这对我帮助很大:) 虽然 set_shutdown_function 应该是 register_shutdown_function()。还有??符号不被接受,这个想法是可靠的!
  • 你是对的!修复了代码。这 ??运算符需要php7。
猜你喜欢
  • 2015-08-26
  • 2015-11-18
  • 2014-02-28
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多