自定义 Spatie Laravel-权限异常消息

Customizing Spatie Laravel-Permission Exception Message

我在 Laravel 5.8 API 应用程序中添加了 Saptie Laravel Permission Package。一切正常,当非管理员用户尝试访问管理员特定路由时出现异常。

然而,默认异常呈现为 HTML 403 User does not have the right roles。考虑到我在 API 应用程序中使用它,我想 return 我自己的自定义消息来处理此类异常。

我尝试检查 auth()->user()->hasRole('admin'),但仍然得到相同的默认异常页面。这是我的代码

路线

Route::post('products', 'ProductController@store')->middleware('role:super-admin|admin'); // create a new product

控制器方法

if (auth()->user()->hasRole('admin')) {

    // create & store the product
    $product = Product::create($request->all())

    // return new product
    $responseMessage    = 'Successful operation';
    $responseStatus     = 200;
    $productResource    = new ProductResource($product);

    return response()->json([
        'responseMessage'   => $responseMessage,
        'responseStatus'    => $responseStatus,
        'product'           => $productResource
    ]);
} else {

    return response()->json([
        'responseMessage'   => 'You do not have required authorization.',
        'responseStatus'    => 403,
    ]);
}

为什么我的自定义消息没有显示?

因为您通过 role 中间件保护您的路由,所以 UnauthorizedException 将在您的控制器代码到达之前被抛出。

你可以做的是使用 laravels 异常处理程序 render 方法并检查异常类型和 return 你自己的响应:

来自 docs:

The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response

app/Exceptions/Handler.php

use Spatie\Permission\Exceptions\UnauthorizedException;

public function render($request, Exception $exception)
{
    if ($exception instanceof UnauthorizedException) {
        return response()->json([
            'responseMessage' => 'You do not have required authorization.',
            'responseStatus'  => 403,
        ]);
    }

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