Is it possible to use an exception with a database query?

Is it possible to use an exception at the end of a mysql query instead of die ()? I would like to make an exception and write it instead of killing the script.

It would be like this:

mysql_query(...) or throw new exception()??
+3
source share
4 answers

So I usually do it. I have my database in a wrapper class, so it $thisjust references 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;
}

For me, this is all with a good error message, so I see the problem. Of course, you could make it a lot easier and do:

mysql_query($sql) or throw new Exception("Problem with query: ".$sql);
+1
source

Yes. You can use an exception almost everywhere you have traditionally used die/exit.

0
source

, , script.

0

:

mysql_query(...) or throw new Exception("Failed to run query");

, . , :

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 special 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 this helps!

0
source

Source: https://habr.com/ru/post/1728101/


All Articles