Thursday, April 30, 2015

Throwing Your Own Library Exceptions in PHP

In the previous post, we saw the difference between errors and exceptions, how exceptions can be useful and created our custom exception handler. In this post, we will look how we can create custom exceptions specific to our application, library or company. We also talk about SPL Exceptions that should be used in your code where possible as best practice.

Background

Let's start with bit of background. If you worked on PHP's DOM, PDO, MySQLi or some other extensions or frameworks such as Symphony, Laravel, Slim or any other third party libraries, you might have noticed usually they throw their own exceptions:

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

In case of wrong database connection, it would throw PDOException:

PDOException: SQLSTATE[HY000] [1045] Access denied for user 'dbuser'@'localhost'

Where did PDOException come from ? Or how did PDO gave that exception ? It is simple. As I had pointed out in my previous postException is a class like any other normal class that can be extended. That's exactly what PDO does here, it simply extends the Exception class so PDO extension should be doing something like this under the hood to be able to throw PDOException:

class PDOException extends Exception {}

And that's usually it. And then PDO should now be throwing that new exception instead of Exception:

// something went wrong
throw new PDOException('message here');

And then user of PDO sees those PDOExceptions.

Now that we know PDOException actually extends Exception, we can come to conclusion that we can catch exceptions thrown by PDO either by using PDOException or Exception through nested catch blocks. If exception is NOT caught for PDOException, it will fall back to base Exception:

try{
    // any PDO code here
}
catch(PDOException $e){
    // handle PDOException
}
catch(Exception $e){
    // handle Exception
}

Throwing Your Own Exceptions

As said above, we can throw our own exceptions by extending the Exception class:

class MyAwesomeLibraryException extends Exception {}

or

class MyCompanyException extends Exception {}

That's easy but one might ask why throw custom exceptions? I can see these reasons:

  • It makes it easy to recognize which thing (library, class, extension, etc) generated exception in code hierarchy
  • This helps developer of orginal library easily spot problems in their code
  • It brands your library exceptions like PDO, DOM, etc do.

Now as developer of some library/application, any time we find we need to throw exception, we simply throw our own custom exceptions:

// something wrong, throw our custom exception
throw new MyAwesomeLibraryException('some message');

Of course you can have many exception types as well for your application if you want.

Prioritizing Your Own Exceptions

Imagine we want to create our own ORM library called SuperORM and it uses PDO under the hood. We create our custom exception first:

class SuperORMException extends PDOException {}

And now we throw SuperORMException exception from whole of our ORM where needed. But since we are using PDO under the hood, we get its PDOException as well and we don't want to show this directly to the consumers of our SuperORM library, we want to be able to first show them our own exception type. This is how we can do that:

class SuperORMException extends PDOException {}

class SuperORM {
    public function connect($dsn, $user, $password) {
        // try connecting to database
        try {
            $dbh = new PDO($dsn, $user, $password);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch (PDOException $e) {
            throw new SuperORMException($e->getMessage(), null, $e);
        }        
    }
}

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$superORM = new SuperORM;
$superORM->connect($dsn, $user, $password);

And that would result in our SuperORMException:

SuperORMException: SQLSTATE[HY000] [1045] Access denied for user 'dbuser'@'localhost'

And consumer of our SuperORM can catch our exception now:

try {
    $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
    $user = 'dbuser';
    $password = 'dbpass';

    $superORM = new SuperORM;
    $superORM->connect($dsn, $user, $password);
}
catch (SuperORMException $e) {
    echo $e->getMessage();
}

This makes sure consumer of library will now know that SuperORM will always throw exception of type SuperORMException.

We see that SuperORMException extends PDOException and PDOException extends Exception, this gives consumer the opportunity to catch exceptions in those types like so:

try {
    $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
    $user = 'dbuser';
    $password = 'dbpass';

    $superORM = new SuperORM;
    $superORM->connect($dsn, $user, $password);
}
catch (SuperORMException $e) {
    // code to catch exception
}
catch (PDOException $e) {
    // code to catch exception
}
catch (Exception $e) {
    // code to catch exception
}

So that's how you can throw your own custom exceptions. In fact that's how some of the ORMs or database libraries from various framework do and throw their own exceptions for consumers to catch.

Don't Always Throw Your Custom Exceptions

By this I mean there are certain exceptions types that are part of Standard PHP (SPL) known as SPL Exceptions. They are made to be thrown for specific reasons and considered best practice. You should throw SPL Exceptions where applicable instead of your own custom exceptions. Here they are:

As can be seen, those exceptions can be broadly divided into two main categories: LogicException and RuntimeException. All of those exceptions are self-explanatory from their names. For example LogicException represent any errors caused by the logical errors in your code, RuntimeException represent any errors that are caused after script has run eg runtime errors; similarly BadMethodCallException exception should be thrown if a method in your class doesn't exist and so on.

These SPL exceptions are excellent addition to PHP core because previously if call was made to some method which didn't exist, you usually communicated that to user through a message like:

throw new Exception('Method does not exist!');

So you communicated through those messages for different types of problems. The problem here was that we needed specific exceptions; if method didn't exist, we needed BadMethodCallException exception. This clearly tells developer what type of exception it is and why it might have come about. Another benefit is that such exceptions are useful even for Non-English speaking developers who can also easily spot the problem. Therefore, you must use SPL exceptions for different situations they are made for.

Wednesday, April 29, 2015

Exceptions Are Bad Yet Awesome!

Overview

At first thought, the words errors and exceptions give the general idea that they are the same thing or collectively errors especially to the beginners. For example, when we see this:

Fatal error: Call to undefined method Foo::bar()

Or this:

Exception: Method is not callable by this object

Most beginner developer would concluded that those are just errors that need to be fixed and that may be right in a superficial sense because both of those messages are bad and need to be fixed anyway but in reality they are different things. The first one is an Error while later one is an Exception. Once we understand there can be both errors and exceptions and how to successfully handle each, we can surely write better code.

In this post, we will see how we can deal with both of them and even create our own custom error and exception handlers for more control over how we want them to be displayed or handled while following best practices.

Difference between Errors and Exceptions

Errors

  • Errors are errors that are emitted by the programming language and you need to fix them.

  • There can be syntax errors or logic errors. In PHP, there are different levels of errors such as ERRORPARSEWARNINGNOTICESTRICT. Some errors levels halt the further execution of your PHP script (such as FATAL errors) while others allow it to continue while presenting useful information that might also need to be fixed or payed attention to such as WARNING or NOTICE. And finally there are other error levels that can tell whether a particular function is deprecated (DEPRECATED) or whether or not standards are being followed (STRICT).

  • Errors can be converted into user-thrown exceptions while still some being recoverable other not because they are emitted by core programming language

  • We can emit custom/user errors through trigger_error() function

  • We can create custom error handler for all errors using set_error_handler()

  • The error_get_last function can be used to get any error that happened last in PHP code. The $php_errormsg variable can be used to get previous error message.

Exceptions:

  • Exceptions are object oriented approach to errors and are thrown intentionally by code/developer and should be handled/caught using try - catch -finally blocks

  • An Exceptionis a standard class that can be used like any other class and can also be extended.

  • Exceptions can have many types (through sub-classes) while errors can only have levels mentioned above.

  • Exceptions can be caught at any point in the call stack and can also be caught at root/default exception handler. In comparison, errors are only handled in pre-defined error handler.

  • We can throw custom/user exceptions by using throw new Exception(...)

  • We can create custom exception handler for all exceptions using set_exception_handler()

General Practice

Nowadays, it seems common (and better) practice to always throw exceptions (even for errors) from your code so that they can be caught and dealt with in caller script. Of course if we throw an exception for error which is FATAL, we can't recover from it but we can still provide OOP approach to caller script. If you have used MySQL extension, you would notice that it emits normal errors if something goes wrong; here is an example when connection to database could not be made:

Warning: mysql_connect(): Access denied for user 'root'@'localhost'

Notice that it emits error level of Warning. This is just an example for the function mysql_connect but other functions of MySQL extension also emit errors in the same way and can be grabbed with mysql_error() function.

But if you use improved version of MySQL called MySQLi or even PDO, you would notice they can now also throw exceptions, here is same example if connection could not be made to database using mysqli:

mysqli_report(MYSQLI_REPORT_STRICT); // tell mysqli to generate exceptions as well
mysqli_connect('localhost', 'root', 'wrongPassword', 'test');

It would give you both error as well as exception:

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Access denied for user 'root'@'localhost'

mysqli_sql_exception: Access denied for user 'root'@'localhost' (using password: YES)

So these days any good written package or library or some extension you use, it would most likely generate Exceptions of its own type so that they can be caught and handled gracefully.

How Do Exceptions Help ?

Let's understand through example. Let's say you want to connect to database using mysql and you would normally do something like this:

mysql_connect('localhost', 'root', 'wrongPassword', 'test');

If connection could not be made to database, you would receive error:

Warning: mysql_connect(): Access denied for user 'root'@'localhost'

Now the only thing you can do is go to your code and edit it to specify correct database credentials.

Let's now do the same thing using mysqli:

mysqli_report(MYSQLI_REPORT_STRICT); // tell mysqli to generate exceptions as well
mysqli_connect('localhost', 'root', 'wrongPassword', 'test');

This would generate an error as well as exception as shown previously. Since exception is generated, we can catch it and show the message:

try {    
    mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
} catch (mysqli_sql_exception $e) {
    echo $e->getMessage();
}

The reason why exception is useful here is because you are given a chance to catch that exception gracefully. Inside catch block, we can handle the exception however we want. For the sake of example, let's say we want to connect to database again with correct password this time:

mysqli_report(MYSQLI_REPORT_STRICT);

try {    
    mysqli_connect('localhost', 'root', 'wrongPassword', 'test');
} catch (mysqli_sql_exception $e) {
    mysqli_connect('localhost', 'root', 'rightPassword', 'test');
}

And thanks to exception, we were able to catch it and handle it the way we needed and we are now connected to database which was simply not possible with previous example using mysql which only emitted an error and we couldn't do much. Of course in real world applications, you might not have different passwords to connect to database but this example just gives an idea of how exceptions can be useful.

As another example, let's say we want read feed/rss of some website using SimpleXML (which can also throw exceptions) and store 10 posts in an array:

$feedUrl = 'http://some_feed_url';
$feeds = file_get_contents($feedUrl);
$xml = new SimpleXmlElement($feeds);

$articles = array();
foreach ($xml->channel->item as $item) {
   $item = (array) $item;
   $articles[] = array('title' => $item['title'], 'link' => $item['link']);
}

$data['articles'] = array_slice($articles, 0, 10);

This would work as long as feed url is correct and has posts but if url is wrong, you would see a Fatal error as well Exception being generated by the script:

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML

Exception: String could not be parsed as XML

Since it is FATAL error, our script died at that point and we can't do anything. How do we ensure that our script continues working and runs any code below that feed code even if provided feed url was wrong ? Of course we need to catch the exception since as we saw it also generated an Exception:

try {
    $feedUrl = 'http://some_feed_url';
    $feeds = file_get_contents($feedUrl);
    $xml = new SimpleXmlElement($feeds);

    $articles = array();
    foreach ($xml->channel->item as $item) {
       $item = (array) $item;
       $articles[] = array('title' => $item['title'], 'link' => $item['link']);
    }

    $data['articles'] = array_slice($articles, 0, 10);
} catch (Exception $e) {

}

echo 'Hello World';

And now since we have wrapped our code in try-catch and caught the exception, our code below that should still run. In this case even if feed url was wrong, you should still see the Hello World message. Our script didn't die and continued its execution. So those two examples should now give idea of how useful exceptions can be when used.

How do I convert Errors into Exceptions?

To do so ,we can use the set_error_handler() function and throw exceptions of type ErrorException something like:

set_error_handler(function ($errorNumber, $errorText, $errorFile, $errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});

With that custom exception now in place, you can do things like:

try {
    // wrong url
    file_get_contents('http://wrong_url');
} catch (ErrorException $e) {
    // fix the url
    file_get_contents('http://right_url');
}

So in catch block, we are now able to fix the URL for the file_get_contents function. Without this exception, we could do nothing but may be suppressing the error by using error control operator @.

Universal Exception Handler

Now that we have seen how useful exceptions are and how to convert errors into exceptions, we can create our custom universal exception handler that can be used throughout the application. It will always generate exceptions not errors. It will do these things:

1 - Allow us to tell it our environment which can be either development or production

2 - In case of production environment, it will log all errors to a file instead of displaying them on screen

3 - In case of development environment, it will display all errors on the screen

/**
 * A class that handles both errors and exceptions and generates an Exception for both.
 *
 * In case of "production" environment, errors are logged to file
 * In case of "development" environment, errors are echoed out on screen
 *
 * Usage:
 *
 * new ExceptionHandler('development', '/myDir/logs');
 *
 * Note: Make sure to use it on very beginning of your project or bootstrap file.
 *
 */
class ExceptionHandler {
    // file path where all exceptions will be written to
    protected $log_file = '';
    // environment type
    protected $environment = '';

    public function __construct($environment = 'production', $log_file = 'logs')
    {
        $this->environment = $environment;
        $this->log_file = $log_file;

        // NOTE: it is better to set ini_set settings via php.ini file instead to deal with parse errors.
        if ($this->environment === 'production') {
            // disable error reporting
            error_reporting(0);
            ini_set('display_errors', false);
            // enable logging to file
            ini_set("log_errors", true);
            ini_set("error_log", $this->log_file);
        }
        else {
            // enable error reporting
            error_reporting(E_ALL);
            ini_set('display_errors', 1);
            // disable logging to file
            ini_set("log_errors", false);
        }

        // setup error and exception handlers
        set_error_handler(array($this, 'errorHandler'));
        set_exception_handler(array($this, 'exceptionHandler'));        
    }

    public function exceptionHandler($exception)
    {
        if ($this->environment === 'production') {
            error_log($exception, 3, $this->log_file);
        }

        throw new Exception('', null, $exception);
    }

    public function errorHandler($error_level, $error_message, $error_file, $error_line)
    {
        if ($this->environment === 'production') {      
            error_log($message, 3, $this->log_file);
        }

        // throw exception for all error types but NOTICE and STRICT
        if ($error_level !== E_NOTICE && $error_level !== E_STRICT) {
            throw new ErrorException($error_message, 0, $error_level, $error_file, $error_line);
        }        
    }
}

Test it:

// register our error and exceptoin handlers
new ExceptionHandler('development', 'logs');

// create error and exception for testing
trigger_error('Iam an error but will be converted into ErrorException!');
throw new Exception('I am an Exception anyway!');

So that is an example of basic universal error and exception handler class. Actually you can do a lot more like customizing the display of messages, getting the stack trace as well as code that caused it, creating timestamp for when those events take place, etc. You should checkout the official documentation in order to achieve those goodies. At any point in your code, you want to restore original PHP's error and exception handlers, you can use restore_error_handler() and restore_exception_handler() functions.

Conclusion

No exception to exceptions!


As a side note, I personally hope someday a PSR standard is created for handling errors and exceptions and their best practices because they are integral part of any PHP code.

Popular Posts