答案 0 :(得分:0)
您可以像在{strong>您的控制器中那样,将其作为Exception
来捕获:
try {
// Whatever you are doing which leads to such error.
} catch (MissingScopeException $e) {
return response()->json(['message' => 'YOUR DESIRED MESSAGE.']);
}
顺便说一下,this is where导致了这种异常。
答案 1 :(得分:0)
尝试更新render function
文件中的app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
if ($exception instanceof \Laravel\Passport\Exceptions\MissingScopeException)
{
return response()->json(['message' => 'your message here']);
//abort(401);
}
return parent::render($request, $e);
}
答案 2 :(得分:0)
我正在使用laravel/framework v8.10.0
和laravel/passport v10.0.1
。
如果仅将Passport用于API,则可以直接在中间件中更改throw异常。
步骤:
app/Http/Kernel.php
。$routeMiddleware
数组中,您需要包含以下行:
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class
。CheckForAnyScope
中间件。CheckForAnyScope
中间件中,转到handle
函数并在该行之前:
throw new MissingScopeException($scopes);
添加您的自定义错误响应。示例代码:
public function handle($request, $next, ...$scopes)
{
if (! $request->user() || ! $request->user()->token()) {
throw new AuthenticationException;
}
foreach ($scopes as $scope) {
if ($request->user()->tokenCan($scope)) {
return $next($request);
}
}
// Custom error response
return response()->json(['success' => false, 'errors' => ['This type of user cannot do this action.'], 'data' => null]);
// This line can be commented or deleted.
throw new MissingScopeException($scopes);
}