Arall
Arall

Reputation: 192

PHP chaining error handling

Is a good idea throw exceptions on chained methods?

For example:

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();

Of course, this will fail and cause a fatal error unless we use try / catch.

Otherwise, if we don't thrown an error when addAttachment fails, use will not notice if anything went wrong. And if the send can work without attachments, we cannot return an error on that method neither.

So, there is any good practice on error logging / handling when using chained methods?

Upvotes: 1

Views: 597

Answers (1)

Machavity
Machavity

Reputation: 31614

You should throw an Exception anywhere you want to interrupt the flow of the program. It doesn't matter if it's chained or not. In your case, if the adding of the attachment fails, you want to stop it before it reaches send(). That's a perfectly fine use of an Exception.

Obviously, you need to make sure you wrap the whole execution in try/catch or you'll get a Fatal error (where all PHP stops).

Upvotes: 1

Related Questions