I use the code by going through the tutorial by odan
After that added database connectivity in settings.php [ I use Postgres database ]
$settings[‘db’] = [
‘driver’ => ‘pgsql’,
‘host’ => ‘localhost’,
‘port’ => ‘5433’,
‘database’ => ‘test’,
‘username’ => ‘user’,
‘password’ => ‘pass’,
];
container.php was added with
PDO::class => function (ContainerInterface $container) {
$settings = $container->get(‘settings’)[‘db’];
$host = $settings['host'];
$dbname = $settings['database'];
$username = $settings['username'];
$password = $settings['password'];
$port = $settings['port'];
$dsn = "pgsql:host=$host;port=$port;dbname=$dbname";
return new PDO($dsn, $username, $password);
},
public function insertUser(array $user): array
{
$username = isset($user[0]["username"]) ? $user[0]["username"] : null;
$first_name = isset($user[0]['first_name']) ? $user[0]['first_name'] : null;
$last_name = isset($user[0]['last_name']) ? $user[0]['last_name'] : null;
$email = isset($user[0]['email']) ? $user[0]['email'] : null;
$db = $this->connection;
$db->beginTransaction();
$sql = " Insert into users0 (username, first_name, last_name, email) ";
$sql = $sql . " values (?, ?, ?, ?) ";
try
{
$statement = $db->prepare($sql);
$statement->execute([$username, $first_name, $last_name, $email]);
$db->commit();
return $this->customResponse->is201Response('Success');
}
catch(PDOException $e)
{
$db->rollBack();
return $this->customResponse->is500Response($e->getMessage());
}
}
It works fine when all data is correct. No issues.
When some error occurs (like a Unique key violation, or check constraint), I want to catch those errors and return an appropriate response to the user. I hope PDOException will catch those errors, which is not catching.
I get only is201Response(‘Success’) even when there is either unique key violation or check constraint violations in the data. Would like to know why the PDOException is not catching those errors?
What should I do to catch those errors?
TIA
Krithika