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

I use my own simple error handling and can actually catch everything I need. But now I need to catch the error with try{}catch(){} . The error that I sometimes expect in this place is "Error calling undefined method". 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 general. I would like to catch only this type of error.

Is there a way to limit capture to a specific โ€œtypeโ€ of errors?

Without using strpos($errorMessage) ...;)

+5
source share
2 answers

Using the __call() magic method in your classes can be used to create custom exceptions if the method does not 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

+3
source

I know it's too late after 18 months, but you thought about doing something @Mark Baker , but throw a BadMethodCallException ?

0
source

All Articles