Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^36) CHAPTER 4 ■ EXCEPTIONS
Listing 4-4. Creating a Logging Exception Base Class
class LoggedException extends Exception {
public function construct (
$message=null,
$code=0,
$file='/var/log/phpException.log')
{
$this->log($file);
parent::
construct($message, $code)
}
protected function log($file) {
file_put_contents($file, $this->__toString(), FILE_APPEND);
}
}
■Note For details on the file functions used in Listing 4-4, see the PHP manual at http://www.php.net/
manual/en/ref.filesystem.php.
You can then use LoggedException in place of Exception in all your invocations or custom
exceptions. This will log all exceptions, even those that are caught. This is not always desirable,
as you may wish to log only exceptions that were not caught or that were rethrown by a catch
block. In these cases, you will want to use the PHP function set_exception_handler(), as described
in the next section.


Defining an Uncaught Exception Handler.


The set_exception_handler() function defines what to do when an exception makes it all the
way up your call stack to the main function entry without being caught. Usually, you will see a
message like this:

Fatal error: Uncaught exception 'Exception' in file.php:2
Stack trace:
#0 {main}
thrown in file.php on line 2

This is the built-in exception handler. It can be useful, but it can also expose sensitive
information, such as database login credentials. It is advantageous to disable this handler in
production environments, by using php.ini, .htaccess, or ini_set(). Alternatively, if you wish
to know about the exceptions that occur but still not display those exceptions, you can use the

McArthur_819-9C04.fm Page 36 Friday, February 1, 2008 10:25 AM

Free download pdf