Php 自定义SpatialAvel权限异常消息

Php 自定义SpatialAvel权限异常消息,php,laravel,spatie,Php,Laravel,Spatie,我在Laravel5.8API应用程序中添加了。每一个都可以正常工作,当一个非管理员用户试图访问管理员特定的路由时,我会遇到异常 但是,默认异常呈现为HTML403用户没有正确的角色。考虑到我在一个API应用程序中使用它,我想为此类异常返回我自己的自定义消息 我尝试检查auth()->user()->hasRole('admin')但是仍然得到相同的默认异常页面。这是我的密码 路线 控制器方法 if (auth()->user()->hasRole('admin')) {

我在Laravel5.8API应用程序中添加了。每一个都可以正常工作,当一个非管理员用户试图访问管理员特定的路由时,我会遇到异常

但是,默认异常呈现为HTML
403用户没有正确的角色。考虑到我在一个API应用程序中使用它,我想为此类异常返回我自己的自定义消息

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

路线

控制器方法

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,
    ]);
}

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

因为您正在通过
角色
中间件保护您的路由,
未授权异常将在到达控制器代码之前抛出

您可以使用laravels异常处理程序
render
方法,检查异常类型并返回您自己的响应:

从:

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

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);
}

您发布的代码不会引发
未授权异常
,您是否通过中间件(例如
角色:admin
)保护您的路由?如果是,则永远不会到达控制器,因此永远不会运行代码。@Remul yes我正在调用路由上的
角色:admin
中间件。有关路线,请参见编辑的帖子。如果在点击控制器之前检查了用户角色,那么我该怎么做才能返回json响应而不是呈现html 403页面?我将您的代码添加到app/Exceptions/Handler.php的
render
方法中,但仍然得到默认的异常页面。您是否导入了
UnauthorizedException
?e、 g.
使用空间\权限\异常\未授权异常这已经添加到,谢谢大家!
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);
}