Skip to content

Instantly share code, notes, and snippets.

@samsonasik
Last active March 15, 2016 14:27
Show Gist options
  • Save samsonasik/8056573 to your computer and use it in GitHub Desktop.
Save samsonasik/8056573 to your computer and use it in GitHub Desktop.
zf2 handle fatal error
1. create a file under public/ folder named fatalerrorhandler.php
<?php
//adapt from http://stackoverflow.com/questions/277224/how-do-i-catch-a-php-fatal-error
define('E_FATAL', E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR |
E_COMPILE_ERROR | E_RECOVERABLE_ERROR);
//Custom error handling vars
define('DISPLAY_ERRORS', TRUE);
define('ERROR_REPORTING', E_ALL | E_STRICT);
register_shutdown_function('shut');
set_error_handler('handler');
//catch function
function shut()
{
$error = error_get_last();
if ($error && ($error['type'] & E_FATAL)) {
handler($error['type'], $error['message'], $error['file'], $error['line']);
}
}
function handler($errno, $errstr, $errfile, $errline)
{
switch ($errno) {
case E_ERROR: // 1 //
$typestr = 'E_ERROR'; break;
case E_WARNING: // 2 //
$typestr = 'E_WARNING'; break;
case E_PARSE: // 4 //
$typestr = 'E_PARSE'; break;
case E_NOTICE: // 8 //
$typestr = 'E_NOTICE'; break;
case E_CORE_ERROR: // 16 //
$typestr = 'E_CORE_ERROR'; break;
case E_CORE_WARNING: // 32 //
$typestr = 'E_CORE_WARNING'; break;
case E_COMPILE_ERROR: // 64 //
$typestr = 'E_COMPILE_ERROR'; break;
case E_CORE_WARNING: // 128 //
$typestr = 'E_COMPILE_WARNING'; break;
case E_USER_ERROR: // 256 //
$typestr = 'E_USER_ERROR'; break;
case E_USER_WARNING: // 512 //
$typestr = 'E_USER_WARNING'; break;
case E_USER_NOTICE: // 1024 //
$typestr = 'E_USER_NOTICE'; break;
case E_STRICT: // 2048 //
$typestr = 'E_STRICT'; break;
case E_RECOVERABLE_ERROR: // 4096 //
$typestr = 'E_RECOVERABLE_ERROR'; break;
case E_DEPRECATED: // 8192 //
$typestr = 'E_DEPRECATED'; break;
case E_USER_DEPRECATED: // 16384 //
$typestr = 'E_USER_DEPRECATED'; break;
}
$message = $errfile.'<b>'.$typestr;//.': </b>'.$errstr.' in <b>';
if(!($errno & ERROR_REPORTING))
return;
if (DISPLAY_ERRORS) {
echo "SOMETHING BAD HAPPEN";
//you can do log with $message here for fatal error
}
}
?>
2. include in public/index.php
<?php
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Setup autoloading
require 'init_autoloader.php';
include 'fatalerrorhandler.php';
// Run the application!
@Zend\Mvc\Application::init(require 'config/application.config.php')->run();
?>
Don't forget to add `@` before run Zend\Mvc\Application::init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment