Pretty cool stuff for pretty cool people.

Menu

Error Handling: Throwing PHP exceptions with the mysql_* extension.

Unfortunately, the (outdated) mysql_* extension in PHP does not support exception handling.
Obviously, this is an issue for those of us who want to avail of the flexibility that exceptions can offer. For the most part, developers who use the mysql_* extension tend to carry out their “error handling” like so:

PHP

1

mysql_query($sql,$connection)ordie(mysql_error($connection));

The problem with this approach is that the rest of our application is completely oblivious to any SQL errors that may occur. If the query fails, the script is halted and there is no way to recover. To make matters even worse, the user will be presented with a nasty-looking SQL error.

A better, more-flexible approach would be to throw an exception if the query fails:

PHP

1

2

3

4

$result=mysql_query($sql,$connection);

if($result===false){

thrownewException(mysql_error($connection));

}

The code above checks to see if mysql_query returns a boolean FALSE value. If it does, we assume that an error has occurred. If an error has occurred, we proceed to throw an Exception containing the MySQL error message.

If you’re worried about the extra added code, then you can abstract your exception-throwing into a custom function like so:

PHP

1

2

3

4

5

6

7

functionquery($sql,$conn=null){

$res=mysql_query($sql,$conn);

if($res===false){

thrownewException(mysql_error($conn));

}

return$res;

}

Using this custom function, we can execute our queries like so (and catch any errors):

PHP

1

2

3

4

5

try{

query("SELECT name FROM users",$connection);

}catch(Exception$e){

//Failed

}

Using exceptions can be extremely beneficial when it comes to handling failed SQL queries.
In the vast majority of cases, a failed SQL query indicates that the application is down and that something has gone terribly wrong. In cases like this, shouldn’t catch the exception in question. Instead, you should “handle” it via a custom exception handler. This can be achieved with the function set_exception_handler. An example:

PHP

1

2

3

4

5

6

7

functionapp_error($exception){

header("HTTP/1.1 500 Internal Server Error");

custom_log_function($exception->getMessage());

include'template/error.html';

exit;

}

set_exception_handler('app_error');

Basically, whenever an exception is thrown, our application will automatically call the app_error function above. There, we can log the error, set a 500 internal server error header and provide the user with a custom “error template”.