Is it acceptable to do error handling in php like below? I am not very familiar with ob_start()/ob_clean()/ob_flush()
, so I want to known is there any bad effect to use them? for example, will they affect performance?
<?php
function custorErr()
{
ob_clean();
//echo error message and some other error handling...
die();
}
set_error_handler("custorErr");
ob_start();
?>
<!doctype html>
<!-- html here -->
<html>
<head>
</head>
<body>
demo
</body>
</html>
<?php ob_flush();?>
If this is not the best practice, then is there any better way to clear all the page content when there being error?
I guess your approach would work very fine and if you want to use it repeatedly I think your approach is the best.
Another option is to put the buffering part in a try/catch
-block. And then clean up output buffer if something goes wrong. If it's just one location you want to check this error , I believe this approach would be better.
<?php
try {
ob_start();
?>
<!doctype html>
<!-- html here -->
<html>
<head>
</head>
<body>
demo
</body>
</html>
<?php
ob_flush();
}
catch {Exception $e) {
ob_end_clean(); //OR ob_clean();
echo 'error is ' . print_r($e, true);
}
Some documentation about cleaning up output buffering: