Trigger
EasySwoole\EasySwoole\Trigger
觸發(fā)器,用于主動(dòng)觸發(fā)錯(cuò)誤或者異常而不中斷程序繼續(xù)執(zhí)行。
使用
攔截異常并記錄
比如:在控制器的OnException
中:
protected function onException(\Throwable $throwable): void
{
//攔截錯(cuò)誤進(jìn)日志,使控制器繼續(xù)運(yùn)行
\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');
回調(diào)接管注冊(cè)
通常出現(xiàn)重大異常(支付失敗等)需要進(jìn)行報(bào)警處理,在全局的mainServerCreate
事件中進(jìn)行注冊(cè):
\EasySwoole\EasySwoole\Trigger::getInstance()->onException()->set('notify',function (\Throwable $throwable){
// 自行實(shí)現(xiàn)通知代碼
});
\EasySwoole\EasySwoole\Trigger::getInstance()->onError()->set('notify',function ($msg){
// 自行實(shí)現(xiàn)通知代碼
});
自定義處理類
需要開發(fā)者實(shí)現(xiàn)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('這是自定義輸出的錯(cuò)誤:'.$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());