I'm struggling to get my head around when to use a couple of the PHP SPL Exceptions, specifically in the below scenario,
class MyClass {
protected $data1;
protected $data2;
public function setData1($data1) {
$this->data1 = $data1;
}
public function setData2($data2) {
$this->data2 = $data2;
}
public function invokeProcess() {
$this->validateData();
}
protected function validateData() {
if(!$this->data1) {
// Which Exception do I throw? See explanation below
}
if($this->data1 && $this->data2) {
// Which Exception do I throw? See explanation below
}
}
}
I have a class which is constructed. The user then sets some data on the object, and invokes a process. The first thing this process does is validate the data on the object to make sure required data is present, data combinations are correct, etc, and if they aren't, an Exception needs to be thrown.
So what Exceptions do I throw?
My validation checks for two scenarios really,
For #1, I'm torn between BadMethodCallException, RuntimeException, and LogicException. And for #2, I think it's just a LogicException?
So, which ones so I use?
Note: Before anyone asks, I can't have required data as parameters in the constructor due to some data only being required when other data is set, etc.
If you have to use an SPL exception, that would be RuntimeException. That's the one that refers to an error that can only be detected at runtime (such as bad input data).
LogicException would be an inappropriate choice, as it refers to a logic error in your program, not in the data it receives. Think of a LogicException as a panic button when your program detects that a condition that must always be true is not (contrast this with a condition that should be true for the program to perform its intended function).
BadMethodCallException would also be inappropriate since it represents an
Exception thrown if a callback refers to an undefined method or if some arguments are missing.
Some data your logic needs may be missing, but there's no method call without the correct number of arguments there.
In your shoes I would either define my own exceptions (derived from RuntimeException), or use RuntimeException directly.
Considering that none of the pre-existing exceptions seems to answer your needs, why not create your own exceptions ?
For instance, you could have :
ValidationException, that would extend Exception.ValidationException_MissingDataValidatonException_BadCombinationIf 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