CodeIgniter Forums
Get error save db in method Controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: Get error save db in method Controller (/thread-75925.html)



Get error save db in method Controller - PHS - 03-29-2020

Hello friends!

In my controller I have the call to a model and the method to save the data received in the respective model:

PHP Code:
$my_model = new MyModel();

$my_model->save($data); 


I would like to know how I can handle an exception if something goes wrong in inserting the data into the table without stopping the system from running?

What happens is that I am testing and simulating database errors. I want to handle this error and show the user a message.

For example, if for some reason an error occurs in sending a mandatory field to the table and this data is being sent empty, I want to handle the exception and send a personalized message to the user instead of showing a message from CI4.

I've tried using try catch, affectedRows () and error () but it didn't work.


PHP Code:
if(!$my_model->save($data)) {
    return $message;
}

try {
    $my_model->save($data);
} catch (
Exception $e) {
    return $message;
}
if (
$my_model->save($data)->affectedRows() < 1) {
    return $message;
}

if (
$my_model->save($data)->error() !== null) {
    return $message;



[font=Monaco, Consolas, Courier, monospace][font=Monaco, Consolas, Courier, monospace]None of these codes worked for the case.[/font][/font]

I want to handle this in the controller.

How to make?