问题描述
我为模型创建了一个自定义策略,并且该策略逻辑对于GraphQL突变确实非常有效。我只是想知道我能否以某种方式将自定义错误消息作为GraphQL响应传递?
这是策略类的示例:
use App\Models\MyModel;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class MyModelPolicy
{
use HandlesAuthorization;
public function update(User $user,MyModel $my_object)
{
if (!$my_object->checkSomething()) {
// Throws an exception
$this->deny('My custom error message should be delivered to the GraphQL client..');
}
return true;
}
}
但是异常中的消息被丢弃:
- Laravel 5在这里:https://github.com/illuminate/auth/blob/8f0603a1d5b90c045a1ce5365ead0f0ba20fc6ce/Access/Gate.php#L279-L281
- 或Laravel 6(及以后)在这里:https://github.com/illuminate/auth/blob/478cf31f02831ec45194fec5428f666f85b4f1b0/Access/Gate.php#L277
解决方法
您可以使用try catch引发您的自定义响应,尽管我个人从未在模型中使用过try catch块(仅在控制器中使用)
Get-PowerBiWorkspace | Export-Csv "MyFile.csv"
您可以相应地更改状态代码和消息。
这里的public function update(User $user,MyModel $my_object)
try {
if (!$my_object->checkSomething()) {
// Throws an exception
throw new \Exception('YourCustomException');
$this->deny('My custom error message should be delivered to the GraphQL client..');
}
return true;
}catch (\Exception $e) {
if ($e->getMessage() == 'YourCustomException') {
$data = [
'status' => 'error','message' => 'YourCustomException is not authorized.',];
return response($data,200);
}
}
是HTTP响应对象。
考虑https://lighthouse-php.com/master/digging-deeper/error-handling.html#user-friendly-errors。
webonyx / graphql-php提供了GraphQL \ Error \ ClientAware接口,可由Exceptions实现,以控制将它们呈现给客户端的方式。
默认情况下,关闭调试模式后,不会向客户端显示异常消息。
由于使用$this->deny()
时不能直接控制抛出的消息,因此可以在Lighthouse中注册一个错误处理程序以识别抛出的AuthorizationException
并将其转换为ClientAware
异常。
https://lighthouse-php.com/master/digging-deeper/error-handling.html#registering-error-handlers