I use my own simple error handling and can actually catch&log everything I need. But now I need to catch an error with try{}catch(){}
. The error, that I expect occurring sometimes at that place, is the "Call to undefined method" error. I can catch it like this:
try {
$someObject->someMethodTheObjectDoesntProvide();
} catch (Error $e) {
// do something else
}
But the Error
class in the catch
clause is a bit to generic. I'd like to catch only this type of error.
Is there a way to restrict the catching to a particular "type" of errors?
Without using strpos($errorMessage)
... ;)
Using a magic __call()
method in your classes can be used to throw custom exceptions if a method doesn't exist
class myCustomException extends Exception {
}
class someClass {
public function __call($name, $arguments) {
if (!method_exists($this, $name)) {
throw new myCustomException($name . ' has shuffled the mortal coil');
}
}
}
$someObject = new someClass();
try {
$someObject->someMethodTheObjectDoesntProvide();
} catch (myCustomException $e) {
echo $e->getMessage();
}
我知道我已经超过18个月了,但是你考虑过做@Mark Baker的建议,而是抛出一个BadMethodCallException
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.