【问题标题】:PHP chaining error handlingPHP 链接错误处理
【发布时间】:2015-07-22 12:09:08
【问题描述】:

在链式方法上抛出异常是个好主意吗?

例如:

class Mailer(){

    private $attachment;

    public function addAttachment($attachment){
        if($this->validateAttachment($attachment)){
            $this->attachment = $attachment;
        }

        throw new \InvalidArgumentException('Invalid attachment');
    }

    public function send(){
        [...]
    }

    private function validateAttachment($attachment){
        if($attachment === 'test'){
            return true;
        }

        return false;
    }
}

$mailer = new Mailer();
$mailer->addAttachment('invalid')->send();

当然,除非我们使用 try / catch,否则这将失败并导致致命错误。

否则,如果我们在addAttachment 失败时没有抛出错误,那么如果出现任何问题,使用将不会注意到。 如果send 可以在没有附件的情况下工作,我们也不能在该方法上返回错误。

那么,在使用链式方法时,在错误记录/处理方面有什么好的做法吗?

【问题讨论】:

    标签: php error-handling exception-handling chaining


    【解决方案1】:

    您应该在要中断程序流程的任何地方抛出异常。它是否被链接并不重要。在您的情况下,如果添加附件失败,您希望在它到达send() 之前停止它。这是对异常的完美使用。

    显然,您需要确保将整个执行过程包含在 try/catch 中,否则您将收到致命错误(所有 PHP 都停止)。

    【讨论】:

      猜你喜欢
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      相关资源
      最近更新 更多