pidari
pidari

Reputation: 449

How do I catch Uncaught TypeError fatal error?

I have a method that accepts arguments of type string but they also could be null. How can I catch this fatal error? Fatal error: Uncaught TypeError: Argument 5 passed to Employee::insertEmployee() must be of the type string, null given, in the following code:

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

Upvotes: 22

Views: 22620

Answers (1)

ishegg
ishegg

Reputation: 9947

TypeError extends Error which implements Throwable. It's not an Exception. So you need to catch either a TypeError or an Error:

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

Upvotes: 44

Related Questions