11

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

automatix
  • 14,018
  • 26
  • 105
  • 230
  • 2
    Nope, only different error/exception classes; and this is just a generic `Error` class – Mark Baker May 24 '16 at 17:13
  • I'm not sure if `__call()` will intercept calls to non-existent methods (or only to non-accessible methods), and allow you to throw a custom exception that could then be caught and handed differently to other errors – Mark Baker May 24 '16 at 17:16
  • You probably want to catch any error that happens, not just a specific one. But you could take a specific action within your `catch` block based on the type of error thrown – WillardSolutions May 24 '16 at 17:17
  • Using a magic __call() method in your classes can be used to throw custom exceptions if a method doesn't exist - [Demo](https://3v4l.org/4YGb0) – Mark Baker May 24 '16 at 17:26

2 Answers2

8

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

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • Thank you very much for your answer and demo! Unfortunately it doesn't solve the problem, since it has a very inconvenient limitation: Using this approach assumes, that the class `SomeClass` of the method `someMethodTheObjectDoesntProvide()` has to implement something like a `HasCallMagicMethod` interface. It's normal for non-built-in exceptions&errors, but `Notice` is a built-in one and should be caught without implementing anything special in the "throwing" class. However, the problem cannot be solved another way (yet) and your suggestion is a very good workaround. Thanks for it once again! – automatix Jun 10 '16 at 11:19
1

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

MikeSchinkel
  • 4,947
  • 4
  • 38
  • 46