简体   繁体   中英

Output buffer error handling

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,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM