Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch the "Call to undefined method" error in PHP 7?

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

like image 304
automatix Avatar asked May 24 '16 17:05

automatix


2 Answers

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

Demo

like image 167
Mark Baker Avatar answered Oct 12 '22 10:10

Mark Baker


I know I'm over 18 months too late but have you considered doing what @Mark Baker suggested but instead throw a BadMethodCallException?

like image 38
MikeSchinkel Avatar answered Oct 12 '22 12:10

MikeSchinkel