Is it possible to use an exception at the end of a mysql query instead of die()? I'd like to throw an exception and log it instead of killing the script.
Would it be done like:
mysql_query(...) or throw new exception()??
Is it possible to use an exception at the end of a mysql query instead of die()? I'd like to throw an exception and log it instead of killing the script.
Would it be done like:
mysql_query(...) or throw new exception()??
This is the way I normally do it. I have my database in a wrapper class, so $this
simply refers to the wrapper.
private function throwException($query = null)
{
$msg = mysql_error().". Query was:\n\n".$query.
"\n\nError number: ".mysql_errno();
throw new Exception($msg);
}
public function query($query_string)
{
$this->queryId = mysql_query($query_string);
if (! $this->queryId) {
$this->throwException($query_string);
}
return $this->queryId;
}
That packages it all up with a nice error message for me, so I can see the problem query. You could keep it much simpler of course, and do:
mysql_query($sql) or throw new Exception("Problem with query: ".$sql);
Yes. You can use an exception almost anywhere you'd traditionally use die/exit
.
Your given code would work fine:
mysql_query(...) or throw new Exception("Failed to run query");
But it's using shorthand that is not entirely clear. I personally think that you're better off sacrificing brevity for clarity:
if (false === mysql_query(...)) {
throw new Exception("Failed to run query.");
}
Keep in mind that throwing Exceptions is only useful if you catch them somewhere, and in your case you probably want to use a custom exception:
class DatabaseException extends Exception {}
try {
if (false === mysql_query(...)) {
throw new DatabaseException("Failed to run query.");
}
} catch (DatabaseException $e) {
$logger->log("Database exception: " . $e->getMessage());
}
Hope that helps!