douchujian8124 2015-09-20 21:20 采纳率: 100%
浏览 81
已采纳

输出缓冲区错误处理

Let us assume that an easy snippet is used for templating and is using output control (ob)

public function capture($file, array $args = array())
{
    extract($args, EXTR_SKIP);

    ob_start();

    require $file; //'foo.php'

    return ob_get_clean();
}

And foo.php that has an error (handled by an error handler and shutdown handler)

<?php

echo "before";
echo $someVariable; //$someVariable is undefined here
echo "after";

Output

before <- would like to avoid
some message from the error handler

The question: is it possible to avoid any output from the file upon error?

Yes,

  • 写回答

1条回答 默认 最新

  • dongyanfeng0563 2015-09-20 22:16
    关注

    If you use the shutdown handler rather than the error handler it can clear the output because the error handler can only clear the output before it so anything outputted after it will still render.

    <?php
    
    function error_handler()
    {
        if(error_get_last()) {
            ob_get_clean();
            echo 'An error has occured.';
        }
    }
    
    register_shutdown_function('error_handler');
    
    function capture()
    {
        ob_start();
    
        require 'foo.php';
    
        return ob_get_clean();
    }
    
    echo capture();
    
    // foo.php
    <?php
    
    echo 'before';
    echo $variable;
    echo 'after';
    
    ?>
    

    This will only output 'An error has occured.'

    however using set_error_handler it will output 'An error has occured.after' unless you add a DIE() or something similar to the error handler.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同