Is there a way to make a class such this one:
class DB extends PDO {}
(which for the record has just one method (the constructor) overloading the parent one so that we pass no parameters to the constructor and we connect via configuration file)
be able to throw in any case a custom CustomException
like this:
throw new CustomException($e->getMessage(), 500, array($e->...));
with $e
being an instance of the PDOException
occurred, instead of the default PDOException
, without wrapping all the methods within a try-catch block?
Not sure how typesafe your code has to be (type hints vs duck typing):
You could write a class which does not extend PDO and use it as delegate via the __call magic method. Inside __call() you can catch the actual PDO exception and wrap it in your custom exception. So you still have to write a wrapper, but a rather short one.
You can throw a custom Exception in your own methods. So if you over wrote each PDO method in your extended class, and made them look like this:
public function query($statement) {
try {
parent::query($statement);
} catch (PDOException $exception) {
throw new CustomException(whatever you want to do here);
}
}
This way whenever PDO throws a PDO Exception, it will catch the exception and throw a custom exception of your own. You will have to keep in mind however that PDO uses some other classes like PDOStatement which can create it's own PDOExceptions which you can also overwrite. you can use as your statement class through PDO's method arguments.