Nice error instead of fatal error

Topics: Developer Forum
Jun 4, 2009 at 2:31 PM
Edited Jun 4, 2009 at 2:34 PM

Hi all,

I have the following problem, as some of you might also have. When creating an Excel file I sometimes get Fatal error: Allowed memory size of XXX bytes exhausted, this is a know problem. How can I show a nice error instead of a fatal error? Or just show nothing is good too.

A try-catch won't work because this only catches exceptions and not errors. And set_error_handler('MyErrorHandler') won't work either because, the following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called. And a fatal error is a E_ERROR. See http://php.net/set_error_handler

Are there any other ideas on how to deal with the fatal error?

Thanks in advance

Developer
Jun 6, 2009 at 12:07 PM

I tried this method from a reader comment in the PHP manual:
http://php.net/set_error_handler#35622

At first it looked promising, but I couldn't make it work.

It could catch some fatal errors such as when you're using undefined functions:
Fatal error: Call to undefined function...

but not this kind of fatal errors:
Fatal error: Allowed memory size of 1048576 bytes exhausted...

For the last case the script would just terminate immediately.

Your question is still open.

 

Jun 8, 2009 at 11:17 AM

I found the answer http://takanotsume.wordpress.com/2008/07/08/php-catch-a-fatal-error/

error_reporting(false);
register_shutdown_function(array($this,'catchFatalError'));
global $_fatal_error;
$_fatal_error = true;
ob_start();

$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$filename = $title.'.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');

ob_end_flush();
$_fatal_error = false;
exit;

function catchFatalError()
{
    global $_fatal_error;
    if ($_fatal_error)
    {
        echo "FATAL ERROR CATCHED";
    }
}