Skip to content

Commit

Permalink
add shutdown handler to even manage fatal errors
Browse files Browse the repository at this point in the history
We can't catch some errors and they are not passed to the error_handler
either. But we can at least react to them in a shutdown function to show
a friendly message to the user and write our log.
  • Loading branch information
splitbrain committed Aug 12, 2020
1 parent 03e8a69 commit cb4cefe
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions inc/ErrorHandler.php
Expand Up @@ -13,6 +13,7 @@ public static function register()
set_error_handler([ErrorHandler::class, 'errorConverter']);
if (!defined('DOKU_UNITTEST')) {
set_exception_handler([ErrorHandler::class, 'fatalException']);
register_shutdown_function([ErrorHandler::class, 'fatalShutdown']);
}
}

Expand Down Expand Up @@ -57,8 +58,8 @@ public static function fatalException($e)
*/
public static function showExceptionMsg($e, $intro = 'Error!')
{
$msg = hsc($intro).'<br />' . hsc(get_class($e) . ': ' . $e->getMessage());
if(self::logException($e)) $msg .= '<br />More info is available in the _error.log';
$msg = hsc($intro) . '<br />' . hsc(get_class($e) . ': ' . $e->getMessage());
if (self::logException($e)) $msg .= '<br />More info is available in the _error.log';
msg($msg, -1);
}

Expand All @@ -76,14 +77,40 @@ public static function showExceptionMsg($e, $intro = 'Error!')
*/
public static function errorConverter($errno, $errstr, $errfile, $errline)
{

if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting, so let it fall
// through to the standard PHP error handler
return false;
}

throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
}

/**
* Last resort to handle fatal errors that still can't be cought
*/
public static function fatalShutdown()
{
$error = error_get_last();
// Check if it's a core/fatal error, otherwise it's a normal shutdown
if (
$error !== null &&
in_array(
$error['type'],
[
E_ERROR,
E_CORE_ERROR,
E_COMPILE_ERROR,
]
)
) {
self::fatalException(
new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'])
);
}
}

/**
* Log the given exception to the error log
*
Expand Down

0 comments on commit cb4cefe

Please sign in to comment.