如何再次抛出异常并捕获它

时间:2015-10-03 15:50:50

标签: php exception model-view-controller

如果从我的模型中抛出异常,我想在我的$ 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 {}
}

1 个答案:

答案 0 :(得分:0)

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

// 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.";
    }
}