【问题标题】:try catch statement not catching custom exception尝试 catch 语句未捕获自定义异常
【发布时间】:2014-02-06 15:22:38
【问题描述】:

我有一个 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.');
}   

为什么 catch 语句在发生异常时没有得到异常?而是它只是被抛出......而不是被抓住?

【问题讨论】:

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


    【解决方案1】:

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

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

    代替

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

    【讨论】:

    • 就是这样。我忘了添加尾部斜杠。尾部斜杠会将我的命名空间范围放回根目录。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2017-05-24
    • 2014-05-11
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多