php - 如何捕获 Uncaught TypeError fatal error ?

标签 php

我有一个方法接受 string 类型的参数,但它们也可以是 null。我怎样才能捕捉到这个 fatal error ? fatal error :未捕获类型错误:传递给 Employee::insertEmployee() 的参数 5 必须是字符串类型,给定为 null, 在以下代码中:

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();
}

最佳答案

TypeError延伸Error它实现了 Throwable .这不是 Exception .因此,您需要捕获 TypeErrorError:

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

关于php - 如何捕获 Uncaught TypeError fatal error ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46953814/

相关文章:

javascript - 提示框重新创建自身,直到输入正确的字段

php - IN 和 WHERE,以字符串或数组形式传入变量

php - UPS运费计算器

php - 如何合并其中具有相同数据的连续子数组?

php - 向 config/database.php 中的表添加前缀,但有一些异常(exception)

php - 如何在nginx服务器中创建虚拟主机?和 ajax 调用

php - 切http ://somelink/withparams and put it into <a href =""> tags

php - 使用碳对象的 Laravel 数据透视表额外日期时间字段格式(不是时间戳)

php - 如何在 Laravel 中模拟验证规则

php - Zend 框架操作堆栈替代方案