【问题标题】:How to add status in default response passport如何在默认响应护照中添加状态
【发布时间】:2018-12-15 07:49:54
【问题描述】:

我正在 Web 和 App 中开发和应用。对于应用程序的 API,我在 laravel 中使用了 Passport。使用护照我可以创建令牌并使用该令牌验证用户以进行其他 api 访问。但是如果令牌无效,那么它会返回错误消息,如“未经授权”,没有任何状态。如果我想添加错误状态(如 401)和消息“未经授权”,谁能告诉我该怎么做。我必须更改代码以使我的网络代码不受影响。我想要 json 响应,如下所示,json 中有 2 个字段。

状态:401 消息:未经授权

【问题讨论】:

    标签: laravel api laravel-passport


    【解决方案1】:

    您可以处理 api 异常并将其响应格式化为 app/Exceptions/Handler.php

    这里是你可以关注的链接

    Laravel API, how to properly handle errors

    【讨论】:

      【解决方案2】:

      您可以创建一个新的异常处理程序中间件来捕获这些请求并修改它返回的响应。

      例子:

      class oAuthExceptionHandler {
          public function handle($request, Closure $next) {
              try {
                  $response = $next($request);
      
                  if (isset($response->exception) && $response->exception) {
                      throw $response->exception;
                  }
      
                  return $response;
              } catch (\Exception $e) {
                  return response()->json(array(
                      'result' => 0,
                      'msg' => $e->getMessage(),
                  ), 401);
              }
          }
      }
      

      然后,在您的 app/Http/Kernel.php 中,命名您的中间件并将其添加到您的 api 组中:

      protected $routeMiddleware = [
          'oauth_exception' => oAuthExceptionHandler::class,
          ...
      ];
      
      protected $middlewareGroups = [
          ...
      
          'api' => [
              'oauth_exception',
              ...
          ],
      ];
      

      【讨论】:

      • 我已经尝试了你的代码,但仍然只得到 { "message": "Unauthenticated." } 我想要像 { "status":"401" "message": "Unauthenticated." 这样的响应。 }
      • 对不起,我弄错了。现在它的工作正常。谢谢。
      猜你喜欢
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      相关资源
      最近更新 更多