Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^38) CHAPTER 4 ■ EXCEPTIONS
Listing 4-6. Creating an Error Coding Custom Exception
class DatabaseException extends Exception {
const ConnectionFailed = 1;
const LoginFailed = 2;
const PermissionDenied = 3;
public function construct($code=0) {
switch ($code) {
case DatabaseException::ConnectionFailed:
$message = 'Database connection failed';
break;
case DatabaseException::LoginFailed:
$message = 'Login to the database was rejected';
break;
case DatabaseException::PermissionDenied:
$message = 'Permission denied';
break;
default:
$message = 'Unknown Error';
}
parent::
construct($message, $code);


}

}

try {
if(! $conn = pg_connect(...)) {
throw new DatabaseException(DatabaseException::ConnectionFailed);
}
} catch (Exception $e) {
//Output the standardized error message on failure
echo $e->getMessage();
}

With this custom exception, all of your error message strings are centralized in one place.
This will allow you to update the database connection error messages without needing to dig
through a large volume of code.

Type Hinting and Exceptions


In Chapter 1, you learned about types and the instanceof operator. Type hinting is effectively
instanceof meets method signature; function(type $param) would be a type-hinted function.

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

Free download pdf