Re: some questions on PEAR_Error usage
| From: | (Stig Sæther Bakken) | Date: | Tue, 24 Apr 2001 13:31:14 +0000 |
| Subject: | Re: some questions on PEAR_Error usage | ||
| References: | 1 | Groups: | php.pear.general |
| Request: | Send a blank email to pear-general+get-84@lists.php.net to get a copy of this message | ||
[Steven Haryanto <steven@haryan.to>]
> I am developing a coding standard for our projects and I have
> several questions on the usage of PEAR_Error.
>
> 1. Should I create my own "exception" type subclassing from
> PEAR_Error. I know that PEAR_Error is somehow the current
> PHP's way of exception handling. But since there is no
> real exception ('try {...} except(ExcClass)') is it worth
> it to create my own ExcClass? And moreover, I can stuff
> whatever additional info on PEAR_Error's $message, $code,
> $options, $userinfo.
Normally you won't need to subclass PEAR_Error. The cases I can think
of is where you only want the concept of an error code (like in DB),
or if you want to report a lot of extra information.
You can put whatever you want into $message, $code and $userinfo.
$mode and $options are owned by the API though.
> 2. I want to set so that errors raised will print the error
> message complete with the originating object, the user info,
> etc. Any advice on how should I do this?
>
> 3. Should I just always use 'return $this->raiseError(...)'
> instead of 'return new PEAR_Error(...)' if my method
> want to report error?
Yes. The reason is that $this->raiseError() is the one that gives the
"end user" the most error handling flexibility. It's not an absolute
though, if you're making classes for your own use and you don't want
to subclass PEAR, "return new PEAR_Error()" is ok.
> How do you guys find this style:
>
> function method() {
> if ($foo) { // error!
> $this->error = $this->raiseError();
> return 0; // false
> }
> return 1;
> }
>
> ...
>
> if (!$obj->method()) {
> // handle the error
> }
>
> over the current convention:
>
> function method() {
> if ($foo) { // error!
> return $this->raiseError();
> }
> return;
> }
>
> ...
>
> $res = $obj->method();
> if (PEAR::isError($res)) {
> // handle the error
> }
>
> (That is, the reporting method just returns 1/0 status so that
> checking error syntax is simplified). The actual PEAR_Error
> instance is available in $obj->error.
The current convention works for functions and objects/methods. Your
alternative style only works for objects.
- Stig
--
Stig Sæther Bakken <ssb@fast.no>
Fast Search & Transfer ASA, Trondheim, Norway