尝试catch语句没有捕获自定义异常

时间:2014-02-06 15:22:38

标签: php exception-handling controller laravel laravel-4

我有一个Laravel 4型号:

Class Organisation extends Eloquent {

....


/**
 * add user to organisation & assign permission group
 *
 * @param $user User user to add to organisation
 * @param $group String name of the permissions group to add the user to
 * @return void
 */
public function addUser( User $user, $group = 'Editors' )
{
    // make sure the user is not already in the organisation
    if( ! $this->users->contains($user->id) ) 
    {
        // if organisation has no users, force first user as an admin
        if( ! $this->users->count() ) 
            $group = 'Admins';

        if( $group = $this->getGroup( $group ) )
        {
            if( $user->addGroup($group) && $this->users()->attach($user) )
                return true;
        }                  
    }
    else
        throw new UserExistsException( $user->fullName()." already belongs to ".$this->title.".");
}

.... 
}

我还有一个控制器调用此函数/模型:

/**
 * Manage users form processing 
 *
 * @return Redirect
 */
public function postIndex( Organisation $organisation )
{ 
    if( $user = Sentry::findUserByLogin(Input::get('email')) ) 
    {
        try
        {
            if( $organisation->addUser( $user, 'Editors' ) )
                return Redirect::route('organisation-user-index', $organisation->id)
                    ->with('success', '<strong>' . $user->fullName() . '</strong> successfully added.');
        }
        catch(Cartalyst\Sentry\Users\UserExistsException $e)
        {
            return Redirect::route('organisation-user-index', $organisation->id)
                ->with('error', $e);
        }
    }

    return Redirect::route('organisation-user-index', $organisation->id)
        ->with('error', 'Something went wrong. Try again.');
}   

为什么捕获声明在发生时没有得到异常?而它只是被抛出......并没有被抓住?

1 个答案:

答案 0 :(得分:4)

您没有显示所有代码,但看起来您正在使用命名空间,因此您可能需要:

catch(\Cartalyst\Sentry\Users\UserExistsException $e)

而不是

catch(Cartalyst\Sentry\Users\UserExistsException $e)