Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch Uncaught TypeError fatal error?

Tags:

php

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();
}
like image 275
pidari Avatar asked Oct 26 '17 12:10

pidari


1 Answers

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();
}
like image 144
ishegg Avatar answered Sep 22 '22 17:09

ishegg