php - 如何捕获 PHP 7 中的 "Call to undefined method"错误?

标签 php error-handling exception-handling try-catch php-7

我使用我自己的简单错误处理,实际上可以捕获并记录我需要的一切。但现在我需要使用 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();
}

Demo

关于php - 如何捕获 PHP 7 中的 "Call to undefined method"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37419822/

相关文章:

php bbcode 与 mysql 检索

excel - Excel 通过 Outlook 发送电子邮件时如何处理错误?

error-handling - Struts2 错误处理 - 未找到异常堆栈

language-agnostic - 应用程序中各层之间的通信

ajax - 将捕获的ajax异常发送回服务器以执行日志记录?

PHP/MySQL - 不断返回 0

php - 如何在ajax调用中获取响应数据

php - 如何使用 Codeigniter 上传文本文件并将其数据导入到 sql 中?

error-handling - 在 Rust : concating results on Ok 中编写错误

python - 使用额外信息重新引发 HTTPError