如何处理webonyx / graphql-php中的自定义错误?

时间:2019-07-29 19:33:48

标签: php 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/),但不知道该怎么做。你能帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

文档指出,为了自定义引发异常时发送的响应,需要抛出一个自定义的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;
}