如何捕获Uncaught TypeError致命错误?

时间:2017-10-26 12:01:46

标签: php

我有一个方法接受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();
}

1 个答案:

答案 0 :(得分:7)

TypeError扩展Error,实现Throwable。这不是Exception。因此,您需要抓住TypeErrorError

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