繁体   English   中英

自定义Spatie Laravel-Permission Exception消息

[英]Customizing Spatie Laravel-Permission Exception Message

我在Laravel 5.8 API应用程序中添加了Saptie Laravel权限包 每个工作正常,当非管理员用户尝试访问管理员特定路由时,我得到例外。

但是,默认异常将呈现为HTML 403 User does not have the right roles 考虑到我在API应用程序中使用它,我想为这些异常返回我自己的自定义消息。

我试过检查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方法并检查异常类型并返回你自己的响应:

来自文档

render方法负责将给定的异常转换为应该发送回浏览器的HTTP响应。 默认情况下,异常将传递给基类,后者会为您生成响应。 但是,您可以自由检查异常类型或返回自己的自定义响应

应用程序/异常/ 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);
}

暂无
暂无

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

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