fp / universal-error-catcher
轻松捕获和处理所有PHP错误和异常。
1.0.2
2012-09-24 10:16 UTC
Requires
- php: >=5.2.7
This package is auto-updated.
Last update: 2024-09-06 23:51:51 UTC
README
概述
它包装错误和异常处理逻辑。任何异常或错误(甚至是解析和致命错误)都将以相同的方式处理。
该库还提供了两个自定义异常
FatalErrorException
- 致命错误,例如E_ERROR
、E_PARSE
、E_CORE_ERROR
、E_COMPILE_ERROR
SuppressedErrorException
- 可恢复的错误,来自代码中的@
它完全由 phpunit 测试覆盖。
安装
Composer 是安装它的首选方式。
php composer.phar require fp/universal-error-catcher
当您被要求输入版本约束时,输入 * 并按回车。
快速浏览
示例显示了在每个错误上发送电子邮件的最简单方法。
<?php $catcher = new UniversalErrorCatcher_Catcher(); $catcher->registerCallback(function(Exception $e) { $to = 'admin@example.com'; $subject = 'Error: '.$e->getMessage(); $body = (string) $e; mail($to, $subject, $body); }); $catcher->start(); // after the start method is called everything is under your control.
致命错误。
让我们假设我们尝试调用一个不存在的方法。在这种情况下,PHP 将引发一个致命错误。
<?php $catcher = new UniversalErrorCatcher_Catcher(); $catcher->registerCallback(function(Exception $e) { $e instanceof FatalErrorException //true }); $catcher->start(); $anObject->notExistMethod();
或者另一种情况,当我们耗尽内存时。在这种情况下,捕捉器将乐意为我们释放一些已分配的内存。
<?php $catcher = new UniversalErrorCatcher_Catcher(); $catcher->registerCallback(function(Exception $e) { $e instanceof FatalErrorException //true }); $catcher->start(); ini_set('memory_limit', '1K'); str_repeat('foobar', PHP_INT_MAX);
可恢复的错误
默认情况下,PHP 错误(警告等)不会抛出,而是传递到后台的回调函数中。
<?php $catcher = new UniversalErrorCatcher_Catcher(); $catcher->registerCallback(function(Exception $e) { $e instanceof ErrorException //true }); $catcher->start(); echo $undefinedVariable; echo 'the script continue to work. This message will be outputed';
您可以通过将所有错误转换为异常来更改此设置。只需将 setThrowRecoverableErrors
设置为 true。
<?php $catcher = new UniversalErrorCatcher_Catcher(); $catcher->setThrowRecoverableErrors(true); // false by default $catcher->registerCallback(function(Exception $e) { $e instanceof ErrorException //true }); $catcher->start(); echo $undefinedVariable; echo 'the exception is throw. It will never be outputed';
在 @
后面(即抑制的)的错误也会被捕捉。如果您想抛出它们,请将 setThrowSuppressedErrors
设置为 true。
<?php $catcher = new UniversalErrorCatcher_Catcher(); $catcher->registerCallback(function(Exception $e) { $e instanceof SuppressedErrorException //true }); $catcher->start(); @trigger_error('supressed warning', E_USER_WARNING); echo 'the script continue to work. This message will be outputed';
异常
任何未被捕获的异常都将传递给您
<?php $catcher = new UniversalErrorCatcher_Catcher(); $catcher->registerCallback(function(Exception $e) { $e instanceof LogicException //true }); $catcher->start(); throw new LogicException('something strange happened. I am scared.'); echo 'the exception is throw. It will never be outputed';