如何将自定义错误消息从 LoginController 发送到前端?
P粉101708623
P粉101708623 2023-09-16 12:57:17
0
1
628

我在 LoginController 中添加了一项检查来限制用户连接设备的最大数量。

我在 LoginControllerlogin() 方法中添加了以下内容:

public function login(Request $request)
{
    // ... some code ...

    if ($this->attemptLogin($request)) {
        $user = Auth::user();
        if ($user->max_devices >= 5) {
            // if I dd() instead of returning this, it gets here
            return $this->sendMaxConnectedDevicesResponse($request);
        }
    }

    // ... some code ...
}

protected function sendMaxConnectedDevicesResponse(Request $request)
{
    throw ValidationException::withMessage([$this->username() => ['Device limit reached'])->status(403);
}

sendMaxConnectedDevicesResponse 是带有我的自定义消息的 sendLockoutResponse 的副本,但是我收到警告,提示我有未处理的异常 (Unhandled \Illuminate\Validation\ValidationException< /代码>)。

那么我该如何像 sendLockoutResponse 处理它一样处理它,这样它就会在前端显示为错误,而不是仅仅忽略它?现在,发生的情况是,即使它抛出错误,它也不会在前端显示它,并且继续照常登录

我只是没有找到正确抛出和捕获自定义错误的方法

P粉101708623
P粉101708623

全部回复(1)
P粉052686710

在我的一个项目中,我使用了这个

throw ValidationException::withMessages([
    'key' => 'error message',
]);

在你的中,你可以使用

throw ValidationException::withMessages([
    'device_limit' => 'Device limit reached',
]);

因此,在前端,您可以使用 device_limit 键获取错误。


在您的登录控制器中

use Illuminate\Http\Request;
use Illuminate\Http\Exceptions\HttpResponseException;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected function authenticated(Request $request, $user)
    {
        if ($user->max_devices >= 5) {
            // Logout the user right after login
            $this->guard()->logout();

            // Throw an instance of HttpResponseException
            throw new HttpResponseException(
                response()->json(['error' => 'Device limit reached'], 403)
            );
        }
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!