我使用我自己的简单错误处理,实际上可以捕获并记录我需要的一切。但现在我需要使用 try{}catch(){}
捕获错误。我预计有时会在那个地方发生的错误是“调用未定义的方法”错误。我可以这样捕捉它:
try {
$someObject->someMethodTheObjectDoesntProvide();
} catch (Error $e) {
// do something else
}
但是 catch
子句中的 Error
类有点过于通用。我只想捕获这种类型的错误。
有没有办法将捕获限制为特定“类型”的错误?
不使用 strpos($errorMessage)
... ;)
最佳答案
在你的类中使用一个神奇的 __call()
方法可以用来在方法不存在时抛出自定义异常
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();
}
关于php - 如何捕获 PHP 7 中的 "Call to undefined method"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37419822/