php - 如何处理 webonyx/graphql-php 中的自定义错误?
问题描述
我正在使用 webonyx/graphql-php 创建一些 graphql 查询,并且文档非常不完整,解释了如何在解析查询期间处理自定义错误。例如,如果用户应用程序发送查询以查找某些记录,我想返回一个自定义错误“未找到客户”,而不仅仅是这个丑陋的结构
[
'debugMessage' => 'Actual exception message',
'message' => 'Internal server error',
'category' => 'internal',
'locations' => [
['line' => 10, 'column' => 2]
],
'path' => [
'listField',
0,
'fieldWithException'
],
'trace' => [
/* Formatted original exception trace */
]
];
我读了很多次文档(https://webonyx.github.io/graphql-php/error-handling/),但不明白该怎么做。请问你能帮帮我吗?
谢谢!
解决方案
文档指出,为了自定义抛出异常时发送的响应,需要抛出一个实现接口并在方法中返回的自定义Exception
类。ClientAware
true
isClientSafe
也就是说,您需要声明一个Exception
类,如下所示:
class CustomerNotFound extends \Exception implements ClientAware
{
protected $message = 'Customer not found';
public function isClientSafe()
{
return true;
}
public function getCategory()
{
return 'missing';
}
}
并且在你的应用程序逻辑中,当没有找到客户记录时,抛出上面的异常类,类似于:
if ($rowCount < 1)
{
throw new CustomerNotFound;
}
推荐阅读
- selenium - 如果使用 FindBy 注释,Selenium 检查元素是否存在
- python - 如何在一个长文件中添加多个唯一的 Excel 文件?(Python)
- android - 如何在 OREO 之前从通知徽章中删除计数?
- tcp - 将 coTurn TCP 分配与 DataChannel 一起使用
- php - PHP 7.4.2 [扩展] 在 Windows 上构建错误
- powerbi - 由多列相关表过滤的 DAX 总和
- java - 测验应用程序未在最后一个问题中显示对话框
- docker - 使用 Ansible 和 Docker 仪表板 Grafana 部署的 Red Hat Ceph 3 失败
- flutter - 调用 SetState() 后 SlideAnimation 不再启动
- html - scss动画作品一次