简体   繁体   English

PHP中的异常处理

[英]Exception handling in php

I have this scenario: 我有这种情况:

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;
 }

} }

I want my controller class which calls Amethod1 and Bmethod1 to know the type of exception(s) thrown in the process. 我希望我的调用Amethod1和Bmethod1的控制器类知道在该过程中引发的异常类型。 Is it advisable to rethrow an exception just like it was presented? 是否建议像提出异常一样抛出异常? Do you think the throw-catch-throw-catch-throw structure reasonable in this case? 您认为在这种情况下, throw-catch-throw-catch-throw结构是否合理?

Yes, totally reasonable. 是的,完全合理。 But: your specific example can be simplified from: 但是:您的特定示例可以简化为:

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

To: 至:

public function Amethod1() 
{

    //assuming that Helper is a property of this class
    $this->helper->helperMethod($this);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM