HomePHP Page 4 - Error Handling for Dynamic Twitter Signature Images with PHP
Playing throw and catch - PHP
Over the course of my past two articles I’ve been showing you how to build a script capable of creating and displaying a dynamic signature image containing the latest status from a user’s Twitter feed. In the third installment in this series, I will be demonstrating how to add proper object-oriented error handling to the SignatureImage class.
As I mentioned previously, throw statements don’t do much good in PHP without a catch statement. Knowing where to place them is dependent upon your application. Since this particular application produces a single output (a single Twitter signature image), it’s convenient to catch all of the exceptions in a single location. The class can then either produce an image or not.
The class’s constructor houses the function calls for the entire image creation process. This makes it a convenient spot to place my try and catch blocks. Quite simply, we can wrap the entire contents of the constructor in a try block. Since each of the exception throws throughout our code are called as the result of a function call in the constructor, we never have to worry about having an unhandled exception. This approach also keeps the entire error-handling process completely contained within the class itself. This is a great approach for larger applications that may contain a great number of different classes.
public function __construct($name, $bg_image, $adir)
{
try {
$this->fetchUserInfo(strtolower($name));
$this->fetchAvatar($this->profile_image, $adir);
$this->renderImage();
}
catch (Exception $e) {
die($e->getMessage());
}
}
If at any point during execution, the method calls in the constructor encounter an exception, execution of the method will stop and code execution will jump to the catch block. This results in a call to PHP’s die function, which displays the error message provided by the throw statement that generated the exception before ending code execution.
In this article you learned how to implement PHP's exceptions as a means of error-handling for our Twitter Signature Image class. But don’t go away just yet. In the next article in this series I will show you how to create your own custom exception class to further take control of how errors are handled in PHP by creating a replacement image whenever errors occur. Until next time, keep coding!