【问题标题】:How to handle custom errors in webonyx/graphql-php?如何处理 webonyx/graphql-php 中的自定义错误?
【发布时间】:2019-12-07 04:17:49
【问题描述】:

我正在使用 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/),但不明白该怎么做。你能帮帮我吗?

谢谢!

【问题讨论】:

    标签: php graphql-php


    【解决方案1】:

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

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

    【讨论】:

    • 是的,你是对的!但是在这种情况下(我无法理解)我需要在解析器中调用这个 CustomerNotFound 或者我需要在其他情况下调用?我可以为它创建一个异常,但是......我什么时候可以调用这个实现?非常感谢您的帮助!
    • 是的,如果找不到记录,您将在解析器中抛出异常。
    猜你喜欢
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多