Trigger
EasySwoole\EasySwoole\Trigger
觸發器,用于主動觸發錯誤或者異常而不中斷程序繼續執行。
使用
攔截異常并記錄
比如:在控制器的OnException
中:
protected function onException(\Throwable $throwable): void
{
//攔截錯誤進日志,使控制器繼續運行
\EasySwoole\EasySwoole\Trigger::getInstance()->throwable($throwable);
$this->writeJson(\EasySwoole\Http\Message\Status::CODE_INTERNAL_SERVER_ERROR, null, $throwable->getMessage());
}
直接記錄
\EasySwoole\EasySwoole\Trigger::getInstance()->error('test error');
回調接管注冊
通常出現重大異常(支付失敗等)需要進行報警處理,在全局的mainServerCreate
事件中進行注冊:
\EasySwoole\EasySwoole\Trigger::getInstance()->onException()->set('notify',function (\Throwable $throwable){
// 自行實現通知代碼
});
\EasySwoole\EasySwoole\Trigger::getInstance()->onError()->set('notify',function ($msg){
// 自行實現通知代碼
});
自定義處理類
需要開發者實現EasySwoole\Trigger\TriggerInterface
:
<?php
namespace App\Exception;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\Trigger\Location;
use EasySwoole\Trigger\TriggerInterface;
class TriggerHandel implements TriggerInterface
{
public function error($msg, int $errorCode = E_USER_ERROR, Location $location = null)
{
Logger::getInstance()->console('這是自定義輸出的錯誤:'.$msg);
// TODO: Implement error() method.
}
public function throwable(\Throwable $throwable)
{
Logger::getInstance()->console('這是自定義輸出的異常:'.$throwable->getMessage());
// TODO: Implement throwable() method.
}
}
在initialize
事件中注入自定義trigger
處理器:
\EasySwoole\EasySwoole\Trigger::getInstance(new \App\Exception\TriggerHandel());