【发布时间】: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