提交 2a1c840d 编写于 作者: O overtrue

Improve exception handle.

上级 27a86912
......@@ -131,10 +131,12 @@ $easySms->send(13188888888, [
```php
[
'yunpian' => [
'gateway' => 'yunpian',
'status' => 'success',
'result' => [...] // 平台返回值
],
'juhe' => [
'gateway' => 'juhe',
'status' => 'failure',
'exception' => \Overtrue\EasySms\Exceptions\GatewayErrorException 对象
],
......@@ -144,6 +146,15 @@ $easySms->send(13188888888, [
如果所选网关列表均发送失败时,将会抛出 `Overtrue\EasySms\Exceptions\NoGatewayAvailableException` 异常,你可以使用 `$e->results` 获取发送结果。
你也可以使用 `$e` 提供的更多便捷方法:
```php
$e->getResults(); // 返回所有 API 的结果,结构同上
$e->getExceptions(); // 返回所有调用异常列表
$e->getException($gateway); // 返回指定网关名称的异常对象
$e->getLastException(); // 获取最后一个失败的异常对象
```
## 自定义网关
本拓展已经支持用户自定义网关,你可以很方便的配置即可当成与其它拓展一样的使用:
......
......@@ -25,6 +25,11 @@ class NoGatewayAvailableException extends Exception
*/
public $results = [];
/**
* @var array
*/
public $exceptions = [];
/**
* NoGatewayAvailableException constructor.
*
......@@ -35,6 +40,42 @@ class NoGatewayAvailableException extends Exception
public function __construct(array $results = [], $code = 0, Throwable $previous = null)
{
$this->results = $results;
parent::__construct('All the gateways have failed.', $code, $previous);
$this->exceptions = \array_column($results, 'exception', 'gateway');
parent::__construct('All the gateways have failed. You can get error details by `$exception->getExceptions()`', $code, $previous);
}
/**
* @return array
*/
public function getResults()
{
return $this->results;
}
/**
* @param string $gateway
*
* @return mixed|null
*/
public function getException($gateway)
{
return isset($this->exceptions[$gateway]) ? $this->exceptions[$gateway] : null;
}
/**
* @return array
*/
public function getExceptions()
{
return $this->exceptions;
}
/**
* @return mixed
*/
public function getLastException()
{
return $this->exceptions[end($this->exceptions)];
}
}
......@@ -70,6 +70,7 @@ class Messenger
foreach ($strategyAppliedGateways as $gateway) {
try {
$results[$gateway] = [
'gateway' => $gateway,
'status' => self::STATUS_SUCCESS,
'result' => $this->easySms->gateway($gateway)->send($to, $message, new Config($gateways[$gateway])),
];
......@@ -78,11 +79,13 @@ class Messenger
break;
} catch (\Throwable $e) {
$results[$gateway] = [
'gateway' => $gateway,
'status' => self::STATUS_FAILURE,
'exception' => $e,
];
} catch (\Exception $e) {
$results[$gateway] = [
'gateway' => $gateway,
'status' => self::STATUS_FAILURE,
'exception' => $e,
];
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册