首页 > 解决方案 > 如果从未达到 return 语句,为什么要返回 void?

问题描述

这是一个有点不同的问题,因为它与我的代码没有直接关系,而是与导致另一个问题中的问题的代码直接相关。

在挖掘与其他问题相关的代码时,我发现了一个return我不理解的奇怪声明。在继续我的问题之前,请看一下代码中的这两个代码片段laravel/framework

特征\Illuminate\Foundation\Auth\AuthenticatesUsers

/**
 * Handle a login request to the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
 *
 * @throws \Illuminate\Validation\ValidationException
 */
public function login(Request $request)
{
    $this->validateLogin($request);

    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

        return $this->sendLockoutResponse($request);
    }

    if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);
    }

    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    $this->incrementLoginAttempts($request);

    return $this->sendFailedLoginResponse($request);
}

特征\Illuminate\Foundation\Auth\ThrottlesLogins

/**
 * Redirect the user after determining they are locked out.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 * @throws \Illuminate\Validation\ValidationException
 */
protected function sendLockoutResponse(Request $request)
{
    $seconds = $this->limiter()->availableIn(
        $this->throttleKey($request)
    );
    throw ValidationException::withMessages([
        $this->username() => [Lang::get('auth.throttle', ['seconds' => $seconds])],
    ])->status(429);
}

AuthenticatesUserstrait 中,检查是否对给定用户进行了过多的身份验证尝试。如果是这样,则会触发一个事件并返回一个锁定响应。到目前为止,一切都很好。

我不明白的是return前面的陈述$this->sendLockoutResponse($request)。给定的方法总是抛出异常并且什么都不返回(好吧,它会返回void,但它不会,因为它总是throws)。

那么return这里声明的目的是什么?是在暗示读者此时login()取消了,还是这是我以前从未听说过的一些特殊语法?

标签: phplaravelexception-handlingreturn

解决方案


推荐阅读