I'm new to php and I am a bit confused by the fact that there seems to be no error object communication from a method to its caller.
These two are the ways I learn to use:
If a method should not info the caller of the error it just triggers an error an if this is not E_USER_ERROR it just can return FALSE to tell the caller something went wrong.
On the other way if a method needs to send back some error info to the caller an exception should be raised.
Coming from COCOA I have learn to use exceptions on extraordinary conditions (non recoverable errors due to programmer mistakes). In any other case just pass an error object to the caller.
PHP has two main mechanisms for indicating and handling errors in your program flow:
Which to pick depends on your personal preference. Exceptions are objects, so if you want to do OOP or come from another language that also uses Exceptions, you might want to use them. Non-Exception based error handling is for all those Notices, Warning and Errors PHP can emit, as well as you own variants of those. If you want to turn these into Exceptions, have a look at ErrorException.
However, like you already mentioned: exceptions are for non-recoverable situations. They are not for managing regular control flow. Consequently, Exceptions are not some sort of standard mechanism to send back error messages to a caller, e.g. you should not do:
class FooValidator
{
public function isValid($valueToValidate)
{
if ($this->satisfiesRules($valueToValidate) {
return true;
}
throw new ValidationException('Foo didnt satisfy rule Bar');
}
}
and they try/catch that in the caller. A failed validation is a recoverable situation.
One option would be to introduce a Notification Object:
class FooValidator
{
public function isValid($valueToValidate, Notification $notification)
{
if ($this->satisfiesRules($valueToValidate) {
return true;
}
$notification->addMessage('Foo didnt satisfy rule Bar');
return false;
}
}
In the above example, the Validator returns only a Boolean but can collect additional information about why the validation failed in the passed Notification object. This is much cleaner than returning an Error Object from the call, because we dont have to check the return type. If the validation returns false, we know we can check the Notification object. Since objects are passed by reference, we dont need to return the object from the call but simply access the collected messages from the caller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With