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

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

Thanks in advance

Jun 6, 2009 at 12:07 PM

I tried this method from a reader comment in the PHP manual:

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

global $_fatal_error;
$_fatal_error = true;

$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');

$_fatal_error = false;

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