如何捕获未捕获的TypeError致命错误?

19

我有一个方法,接受string类型的参数,但它们也可能是null。我该如何捕获这个致命错误?以下是代码:

Fatal error: Uncaught TypeError: Argument 5 passed to Employee::insertEmployee() must be of the type string, null given,
public function insertEmployee(string $first_name, string $middle_name, string $last_name, string $department, string $position, string $passport)
{
    if($first_name == null || $middle_name == null || $last_name == null || $department == null || $position == null || $passport == null) {
        throw new InvalidArgumentException("Error: Please, check your input syntax.");
    }
    $stmt = $this->db->prepare("INSERT INTO employees (first_name, middle_name, last_name, department, position, passport_id) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$first_name, $middle_name, $last_name, $department, $position, $passport]);
    echo "New employee ".$first_name.' '.$middle_name.' '.$last_name.' saved.';
}


try {
    $app->insertEmployee($first_name, $middle_name, $last_name, $department, $position, $passport_id);
} catch (Exception $ex) {
    echo $ex->getMessage();
}

可能是如何捕获PHP致命错误的重复问题。 - castis
我不这么认为。 - pidari
1个回答

39

TypeError 继承自 Error 且实现了 Throwable 接口。它不是一个 Exception,因此您需要捕获 TypeErrorError 中的一个:

try {
    $app->insertEmployee($first_name, $middle_name, $last_name, $department, $position, $passport_id);
} catch (TypeError $ex) {
    echo $ex->getMessage();
}

我明白了。谢谢,但我想显示以下错误消息:“错误:请检查您的输入语法。”我该如何捕获此错误?或者第一个错误在这个错误之前是不可能的吗? - pidari
我想我明白你想要什么了。你为什么要这样做?你本质上是在尝试绕过设计用于实现你想要的语言特性,以便自己来实现它?TypeError 是被特别抛出的,因为期望传入一个 string,但实际传入了一个 null。所以你不需要自己检查,让代码来处理它。你只需在 catch 块中显示错误消息即可。 - ishegg
2
不是愚蠢,只是不知道而已。我们都曾经历过这样的阶段。我们现在也是一样 :)。记得要阅读说明书!祝好运。 - ishegg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接