Trigger

EasySwoole\EasySwoole\Trigger触发器,用于主动触发错误或者异常而不中断程序继续执行。

使用

拦截异常并记录

比如:在控制器的OnException中:

  1. protected function onException(\Throwable $throwable): void
  2. {
  3. //拦截错误进日志,使控制器继续运行
  4. \EasySwoole\EasySwoole\Trigger::getInstance()->throwable($throwable);
  5. $this->writeJson(\EasySwoole\Http\Message\Status::CODE_INTERNAL_SERVER_ERROR, null, $throwable->getMessage());
  6. }

直接记录

  1. \EasySwoole\EasySwoole\Trigger::getInstance()->error('test error');

回调接管注册

通常出现重大异常(支付失败等)需要进行报警处理,在全局的mainServerCreate事件中进行注册:

  1. \EasySwoole\EasySwoole\Trigger::getInstance()->onException()->set('notify',function (\Throwable $throwable){
  2. // 自行实现通知代码
  3. });
  4. \EasySwoole\EasySwoole\Trigger::getInstance()->onError()->set('notify',function ($msg){
  5. // 自行实现通知代码
  6. });

自定义处理类

需要开发者实现EasySwoole\Trigger\TriggerInterface

  1. <?php
  2. namespace App\Exception;
  3. use EasySwoole\EasySwoole\Logger;
  4. use EasySwoole\Trigger\Location;
  5. use EasySwoole\Trigger\TriggerInterface;
  6. class TriggerHandel implements TriggerInterface
  7. {
  8. public function error($msg, int $errorCode = E_USER_ERROR, Location $location = null)
  9. {
  10. Logger::getInstance()->console('这是自定义输出的错误:'.$msg);
  11. // TODO: Implement error() method.
  12. }
  13. public function throwable(\Throwable $throwable)
  14. {
  15. Logger::getInstance()->console('这是自定义输出的异常:'.$throwable->getMessage());
  16. // TODO: Implement throwable() method.
  17. }
  18. }

initialize事件中注入自定义trigger处理器:

\EasySwoole\EasySwoole\Trigger::getInstance(new \App\Exception\TriggerHandel());