我为模型创建了一个自定义策略,并且该策略逻辑对于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;
}
}
但是异常中的消息被丢弃:
答案 0 :(得分:0)
您可以使用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响应对象。
答案 1 :(得分:0)
考虑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