【问题标题】:Dealing with custom exceptions in main script处理主脚本中的自定义异常
【发布时间】:2017-12-19 00:09:56
【问题描述】:

对于这个例子,我使用的是 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());
    }

}

【问题讨论】:

  • 老实说,我认为没有必要将其转换为标准异常,它们已经固有地扩展了基础 Exception 类。
  • 谢谢。这是我尝试的第一件事,但它没有抓住它......但是我现在重试了它,它找到了它。我想我第一次肯定有错字或其他东西。谢谢!
  • 一般来说,这种模式只有在你需要不同的行为时才有用,具体取决于你正在观看的函数抛出的内容。例如,如果存在“超时异常”,您可能会倾向于重试请求而不是“授权异常”,此时您不会这样做。

标签: php exception-handling


【解决方案1】:

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

final class HydrationException extends \RuntimeException implements Exception

2) 您可以对您感兴趣的异常使用 case 语句,并默认您不感兴趣的异常。

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;
}

【讨论】:

    【解决方案2】:
    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 丢失额外的 $response。因此,由您来清理。或者只是在上述函数之外使用 \Mailgun\Exception。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多