Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 4 ■ EXCEPTIONS^35

Listing 4-3. Throwing a Custom Exception

function connectToDatabase() {

if(!$conn = pg_connect(...)) {
throw new DatabaseException("Friendly Message");
}

}

try {

connectToDatabase();

} catch(DatabaseException $e) {
echo $e->getMessage(). "\n";
echo $e->getDatabaseErrorMessage();

}

When thrown, this exception generates the following message:

Friendly Message
Unable to connect to PostgreSQL server: Access Denied for user...

This example exposes not only a friendly message, but also the technical details of why the
connection failed. In most circumstances, you will wish to hide the technical details in a produc-
tion environment, and expose the technical error message only when debugging.

Logging Exceptions


It is often advantageous to log exceptions to a file for later review. You can accomplish this in
either of two ways:


  • Create a custom exception base class for your application.

  • Define an uncaught exception handler.


Let’s look at both techniques.

Logging Custom Exceptions


To define a logging base class, you need to subclass Exception and add a log() method. Place
a call to this logging method in your overridden constructor. Listing 4-4 demonstrates how to
create this logging method.

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

Free download pdf