【问题标题】:How do I throw Exception again and catch it如何再次抛出异常并捕获它
【发布时间】:2015-10-03 15:50:49
【问题描述】:

如果我的模型抛出异常,我想在我的 $message 成员中添加一条消息。

我得到了控制器的异常,但我不知道如何在视图中捕获它。

这是我正在尝试创建的示例。

// This is in my controller //
try {
    if ($this->registerModel->doRegister($credentials) == true) {
        echo "success";
    }
} catch (userAlreadyExistException $e){
    throw $e; // I want this to my view
}

// This is in my Model //
public function doRegister($credential)
{
    if(true){
        throw new userAlreadyExistException();
    }
    return true;
}

// This is my view //
public function getExceptions(){

    try{

    } catch (userAlreadyExistException $e) {
        $this->message = "User already exist in the database";
    }

//I also have this in a own class
class userAlreadyExistException extends Exception {}
}

【问题讨论】:

    标签: php exception model-view-controller


    【解决方案1】:

    我找到了一个更好的解决方案,将接口作为监听器。

    // Create a new interface //
    interface IregisterListener
    {
        public function myIFunction($listener);
    }
    
    // This is in my Model //
    public function doRegister($credential ,IregisterListener $listener)
    {
        if($credential == false){
            $listener->myIFunction("something whent wrong");
        }
        return true;
    }
    
    // This is in my View //
    class myView implements IregisterListener
    {
        public function myIFunction($listener)
        {
            $message = "User exists, pick another username.";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-13
      • 2010-09-25
      • 2018-10-28
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多