Re: Best practice concerning Exceptions
| From: | Michael Gauthier | Date: | Thu, 11 Mar 2010 14:13:56 +0000 |
| Subject: | Re: Best practice concerning Exceptions | ||
| References: | 1 2 | Groups: | php.pear.general |
| Request: | Send a blank email to pear-general+get-30395@lists.php.net to get a copy of this message | ||
On Thu, 2010-03-11 at 10:51 +1030, Daniel O'Connor wrote:
> On Thu, Mar 11, 2010 at 1:07 AM, Auke van Slooten <auke@muze.nl> wrote:
>
> > Hi,
> >
> > I've found the XML_RPC2 package (only after writing my own version of it
> > ofcourse :( ..) and noticed that it declares quite a number of different
> > exception classes. I've read the 'Error Handling Guidelines for PHP5
> > Packages' but couldn't find any information on when to use a new Exception
> > class and when simply to use a new code and message.
> >
> > What is considered good practice for PHP5 exceptions? My own code uses just
> > two exception classes, with about 8 different codes and messages. It seems
> > the XML_RPC2 package throws a specific exception class for each error,
> > skipping error codes.
> >
> >
>
> I find that most people (myself included) just rely on a general category of
> exception; and rarely if ever make use of exception codes.
>
> IE; I'd do:
>
> class Foo {
> public function bar($path) {
> // Checking to ensure things are 'valid' or 'expected' ->
> InvalidArgumentExceptions
> if (!file_exists($path)) {
> throw new InvalidArgumentException("Path must exist");
> }
>
> // Doing the actual business logic; and unexpected things happen
> $content = file_get_contents($path);
> if (empty($content)) {
> throw new InvalidDataException("It looks like the supplied file
> is empty");
> }
> }
> }
>
>
> rather than
>
> throw new FooException("Path must exist", Foo::INVALID_ARGUMENT);
> throw new FooException("It looks like the supplied file is empty",
> Foo::INVALID_DATA);
Hi Auke,
I typically create a new exception class for each category of error and
then use codes to distinguish specific errors in those categories. I
like to use and extend the built-in SPL exceptions where applicable.
For example, in a web service API wrapper, I might have:
* Foo_Exception
* Foo_HttpException
* Foo_AuthenticationException
Then I might have more specific exceptions for specific circumstances.
When deciding whether or not to create a new exception class, I think
about how it would be to write error handling code for the error in
question, and think about how the error should be logged.
Hope this helps,
Mike