我的应用程序入口点中包含以下代码:
try {
/**
* Throws an exception depending on the triggered E_* error type.
*/
$errorHandler = function($errno, $errstr, $errfile, $errline, $errcontext) {
$errorReporting = error_reporting();
if (
// The error was suppressed with the `@` operator
(0 === $errorReporting)
||
// The error code is not included in error_reporting
(!($errorReporting & $errno))
) {
return false;
}
// TODO: Differentiate between the case when this code is executed as the result of an error
// which is handled through the `register_shutdown_function` callback.
throw new \Exception($errstr);
};
set_error_handler($errorHandler);
/**
* Checks for an error which cannot be handled by the handler set through `set_error_handler`.
*/
$shutdownHandler = function() use (&$errorHandler) {
$error = error_get_last();
if (
$error["type"] == E_ERROR
||
$error["type"] == E_PARSE
||
$error["type"] == E_CORE_ERROR
||
$error["type"] == E_CORE_WARNING
||
$error["type"] == E_COMPILE_ERROR
||
$error["type"] == E_COMPILE_WARNING
||
$error["type"] == E_STRICT
) {
$errorHandler($error["type"], $error["message"], $error["file"], $error["line"], []);
}
};
register_shutdown_function($shutdownHandler);
...
}
catch (\Throwable $ex) {
echo '<pre>' . $ex . '</pre>';
}
我的目标是捕获所有PHP错误,异常以及所有内容(甚至包括Fatal error: Allowed memory size of xxx bytes exhausted
之类的错误,我可以通过register_shutdown_function
捕获这些错误),以便使我能够处理所有应用程序的错误/异常(我想显示一个自定义的500页)。
到目前为止,我还没有使用set_exception_handler
。考虑到我已经将整个应用程序的代码包装在try-catch
块中,我想知道是否应该使用它。有必要吗?
感谢您的关注。