开发者

catch exception in a fashionable way

I have an extended class for dateTime who makes some extra validation steps.

When a given date is invalid, it throws an exception.

Now I have some MySQL records with dates in zero (0000-00-00 00:00:00). In those cases, I want to show the text "never", so I have to catch the exception, and now I have this horrible mess...

    try
    {
        $sellDate = new Date();
        $sellDate ->setFromMySQL($this->_data['lastSell']);
        $sellDateDMY = $dateSell->getDMY(TRUE);
    }
    catch (Exception $e)
    {
        if($e->getMessage开发者_StackOverflow() == 'Invalid date.')
            $sellDateDMY = 'Never';
        else
            throw new Exception($e->getMessage());
    }
    $info[] = array('desc' => 'Last Sell: '      , 'data' => $sellDateDMY);

Any better way to do this?


Depends on which method it is that throws. The simplest would be to subclass Date again (maybe as NullableDate?) and override that method to not throw. The getDMY method would then return null, at which point you can display Never using the ternary operator ?:.

This way you won't have to use the ugly try/catch, and the intent of the code will also be clear to anyone who reads it for info on validation requirements -- by instantiating a NullableDate you definitely don't mind if its value is empty.


class DateException extends Exception {
  public function __construct(Exception $e) {
     if($e->getMessage() == 'Invalid date.') {
        $this->message = 'Never';
     } else {
         $this->message = $e->getMessage();
     }
  }
}

try
{
    $sellDate = new Date();
    $sellDate ->setFromMySQL($this->_data['lastSell']);
    $sellDateDMY = $dateSell->getDMY(TRUE);
}
catch (Exception $e)
{
    throw new DateException($e);
 }


You could start throwing different type of exceptions. Specific to the problem. Instead of the generic catch, you could do this

catch (DateInvalidException $de) {
  //code
} catch (DateSomeOtherException $dso) {
 //code
} catch (Exception $e) {
  //general
}

But that's not a good solution. You're mixing up program exceptions and error validations.


Make your own Exception class for your Date functions.

class MyOwnDateException extends Exception {
    ... // Do something or probably nothing
}

And call it in your code:

try {
    if($someErrorYouWantToCatch) {
        throw new MyOwnDateException("error message", 100 /* Error code = optional */);
    }
} catch(MyOwnDateException $mode) {
    $sellDateDMY = 'Never';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜