0

我有这种情况:

Interface ClassInterface 
{
  public function getContext();
}

Class A implements ClassInterface 
{
  public function getContext()
  {
     return 'CONTEXTA';
  }

  //Called in controller class
  public function Amethod1() 
  {
    try {
       //assuming that Helper is a property of this class
        $this->helper->helperMethod($this);
     } catch(Exception $ex) {
       throw $ex;
     }
  }
}

Class B implements ClassInterface 
{
  public function getContext()
  {
     return 'CONTEXTB';
  }

  //Called in controller class
  public function Bmethod1() 
  {
     try {
       //assuming that Helper is a property of this class
        $this->helper->helperMethod($this);
     } catch(Exception $ex) {
       throw $ex;
     }
  }

}

Class Helper {
 public function helperMethod(ClassInterface $interface) 
 {
   try {
      $this->verifyContext($interface->getContext());
      //dosomething
   } catch(\Exception $ex) {
     throw $ex;
   }

 }

 private function verifyContext($context) {
    if (condition1) {
       throw new \UnexpectedValueException('Invalid context.');
    }

    return true;
 }

}

我希望调用 Amethod1 和 Bmethod1 的控制器类知道进程中抛出的异常类型。是否建议像呈现异常一样重新抛出异常?您认为这种情况下的throw-catch-throw-catch-throw结构合理吗?

4

1 回答 1

0

是的,完全合理。但是:您的具体示例可以简化为:

public function Amethod1() 
{
   try {
      //assuming that Helper is a property of this class
      $this->helper->helperMethod($this);
   } catch(Exception $ex) {
      throw $ex;
   }
}

到:

public function Amethod1() 
{

    //assuming that Helper is a property of this class
    $this->helper->helperMethod($this);
}
于 2012-08-12T14:07:02.847 回答