处理主脚本

时间:2017-12-19 00:09:56

标签: php exception-handling

对于此示例,我使用的是Mailgun库。它们提供了5种可以捕获的异常。

我的问题是,在我的主脚本中如何最好地处理?我希望能够捕获所有这些和错误日志,但必须单独捕获所有5个,每次我使用Mailgun都会感到凌乱。

我的想法是采取每一个并抛出一个标准的例外但我不确定这是否正确?

public function sendMailPs($to, $from, $subject, $msgHtml, $msgTxt){

    $mg = Mailgun::create($this->config->key);
    try{
        $res = $mg->messages()->send('domain.com', [
            'from'    => $from,
            'to'      => $to,
            'subject' => $subject,
            'text'=> $msgTxt,
            'html'    => $msgHtml
        ]);
    } catch (HttpClientException $e){
        throw new \Exception($e->getMessage(), $e->getCode());
    } catch (HttpServerException $e){
        throw new \Exception($e->getMessage(), $e->getCode());
    } catch (HydrationException $e){
        throw new \Exception($e->getMessage(), $e->getCode());
    } catch (InvalidArgumentException $e){
        throw new \Exception($e->getMessage(), $e->getCode());
    } catch (UnknownErrorException $e){
        throw new \Exception($e->getMessage(), $e->getCode());
    }

}

2 个答案:

答案 0 :(得分:-1)

1)当异常扩展父类时,您可以通过catch RuntimeException减少重复。

final class HydrationException extends \RuntimeException implements Exception

2)您可以对您感兴趣的例外使用案例陈述,并默认不属于您的案例。

try
{
   // Code here
}
catch( Exception $e )
{
  switch( get_class( $e ) )
  {
    case 'HttpClientException':
    case 'HydrationException':
    case 'UnknownErrorException':
      throw new \Exception($e->getMessage(), $e->getCode());
  }
  throw $e;
}

答案 1 :(得分:-1)

public function sendMailPs($to, $from, $subject, $msgHtml, $msgTxt) {
    $mg = Mailgun::create($this->config->key);
    try{
        $res = $mg->messages()->send('domain.com', [
            'from'    => $from,
            'to'      => $to,
            'subject' => $subject,
            'text'=> $msgTxt,
            'html'    => $msgHtml
        ]);
    } catch (\Mailgun\Exception $e){
        throw new \MailgunException($e->getMessage(), $e->getCode());
    }
}

您可能会丢失来自HttpClientException的额外$响应。因此,您需要清理。或者只是在上面的函数之外使用\ Mailgun \ Exception。