简体   繁体   English

如何在 Laravel/Lumen 中捕捉 401 响应?

[英]How to catch 401 response in Laravel/Lumen?

I am writing an api for authorize users .我正在为授权用户编写一个 api。

With my current code I can catch if response code is 200 however I cannot catch if the response is 401 instead of 200. Instead of an error message with my 401 response, I recieve error page.使用我当前的代码,如果响应代码是200,我可以捕获,但是如果响应是 401 而不是200,我无法捕获。我收到错误页面,而不是带有 401 响应的错误消息。

this is my swagger server in Lumen这是我在 Lumen 中的 swagger 服务器

if($input['phone']==$this->phone && $input['password'] == $this->password){
            return response()->json([
            'redirect_uri' => $redirect_uri,
            'token' => $this->token 
            ]); 
        }

        return response()->json([
            'redirect_uri' => $redirect_uri,
            'errorMsg' => 'User Not found or id psw wrong'
            ],401); 

and this is my model in Laravel这是我在 Laravel 中的模型

if($response->getStatusCode() == 401){
            dd('you are not authorized');
        }

        if($response->getStatusCode() == 200){
            dd('you are authorized');
           //Store user credentials on cache
            CacheStore::storeUserCredentials(json_decode((string) $response->getBody(), true));
        }

basically if statuscode is 200 I recieve this message基本上如果状态码是 200 我收到这条消息

在此处输入图片说明

But if status code is 401 it gives error.但是如果状态代码是 401,它就会出错。

在此处输入图片说明

Apply try catch block to your code将 try catch 块应用于您的代码

try{
  // your api call
}
catch(Exception $e)
{
    if ($e instanceof HttpException && $e->getStatusCode()== 401)
    {
      dd('you are not authorized');
    }
}

I recommend handling universal exceptions in app\\Exceptions\\Handler.php .我建议在app\\Exceptions\\Handler.php处理通用异常。 In this file, there exists a render function.在这个文件中,存在一个render函数。

To deal with different types of Exception, you can try:要处理不同类型的异常,您可以尝试:

public function render($request, Exception $e)
{
    if ($e instanceof SomeTypeException1)
    {
        #handle it
    }
    else if($e instanceof SomeTypeException2)
    {
        #handle it
    }

    return parent::render($request, $e);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM