首页 > 解决方案 > 如何处理 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/),但不明白该怎么做。请问你能帮帮我吗?

谢谢!

标签: phpgraphql-php

解决方案


文档指出,为了自定义抛出异常时发送的响应,需要抛出一个实现接口并在方法中返回的自定义Exception类。ClientAwaretrueisClientSafe

也就是说,您需要声明一个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;
}

推荐阅读