I have a structure project like follow:
/Controller
test.php
/Models
test_model.php
Now when I execute a request the model test.php
shunk the request in the corresponding model, in this case test_model.php
. Here no problem. Now my question is: I should handle the exceptino in test.php
class (controller) or in the test_model.php
class?
For execute all the database dialogue I have created a db layer with pdo. I set the:
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
for handle the exception. All working good but I have this doubt. A practice example:
<?php
include "test_model.php";
public function selectInformation()
{
try
{
$test = new Test_Model(); //just as example..
return $test->selectUserInfo(); // test_model
}catch(Exception $ex)
{
echo json_encode(array("success" => false, "message" => $ex->getMessage()));
exit();
}
}
...
Here the Test_Model
class:
<?php
class Test_Model extends PDO
{
public function __construct()
{
parent::__construct();
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function selectUserInfo()
{
//I removed most part of the code, essentially here an exception is fired by a non correct db table name
}
Actually I manage all the exceptions in the Test
class but is a good practice? I use each Model
only for return a result from the database. There is no each in the Model
class actually.
Neither in the model or controller.
An error exception have to be handled in the error handler.
Instead of "handling" every call to the model separately, you have to handle all errors in a single place. Which is called error handler.
Neither error message or line number should be sent in JSON. This information have to be logged locally, while no internal error have to be revealed outside. Only a generalized excuse have to be shown.
There should be an error handler set through set_error_handler that have to be responsible for handling errors. It should log errors in production, while only a generalized excuse sent outside.
Note that it is very important to send appropriate HTTP status code in case of error, of 5xx family
You should put the try catch block inside your controller.