Cohan Catch Database Exception
I am using Kohana 2. I would like to catch a database exception to prevent an error page when a connection to the server cannot be established.
An error is displayed
system/libraries/drivers/Database/Mysql.php [61]:
mysql_connect() [function.mysql-connect]: Lost connection to MySQL server at
'reading initial communication packet', system error: 110
The database server is currently unavailable.
I am doing this from a model. I tried both
public function __construct()
{
// load database library into $this->db
try
{
parent::__construct();
}
catch (Exception $e)
{
die('Database error occured');
}
}
and
try
{
$hoststatus = $this->db->query('SELECT x FROM y WHERE z;');
}
catch (Exception $e)
{
die('Database error occured');
}
... but none of them seemed to work. It seems that no exception is being passed from the main model. Is there any other way to catch the database error and use my own error handling?
a source to share
You can catch the exception, but you are probably trying to catch it in the wrong place. The problem with trying to catch this low exception rate is that it can be generated from different sources.
For example, if you are using a database driver for your sessions, an exception will be thrown from the database driver instance in the session library (which is thrown when the session is called, which will probably happen before you instantiate any models).
Catching this exception can come from the model, but most likely it will come from a different source - in which case you may need to extend multiple libraries or make sure that you end the call to the underlying model parent::__construct
and the session library in a try-catch block.
(I would personally extend the Model library to do this instead of putting it into the base model)
Hope it helps.
a source to share
I don't know Kohana, but the unit try .. catch
won't catch normal errors, only Exception
s. Are you sure Kohana is throwing Exception
where you expect Exception
s to get ?
Edit based on your comments:
Well, firstly, in a production environment (which means your live application) you should always turn off the display of PHP errors on the screen. Displaying these errors on the screen should only be done in a development environment to inform you, the developer. However, visitors to your real-world application are not experienced in understanding / reading PHP errors, as they may reveal sensitive information about your environment. However, you must log errors in the log file.
Also, I just took a quick look into Kohana and do see exceptions being thrown here and there, but it doesn't seem to be done consistently.
If you want php errors to be handled as exceptions, see example # 1 in this documentation .
a source to share