Query Functions
Query Functions响应错误触发器

响应错误触发器

Included in the “Power Extensions” bundle

在响应中明确添加错误条目,以触发 GraphQL 请求失败(当字段不满足预期条件时)。

说明

此模块添加了字段和指令,用于明确触发错误并向 GraphQL 响应中添加警告。

错误

全局字段 _fail 和指令 @fail 被添加到 GraphQL schema 中,它们会向响应的 errors 属性中添加条目。

query {
  _fail(message: "Some error")
  
  posts {
    featuredImage @fail(
      # condition: IS_NULL, \<= This is the default value
      message: "The post does not have a featured image"
    ) {
      id
      src
    }
  }
  
  users {
    name @fail(
      condition: IS_EMPTY,
      message: "The retrieved user does not have a name"
    )
  }
}

两者都可以接收参数 data,在错误响应中提供上下文信息。

这些 schema 元素在需要明确指示已执行的 GraphQL query 存在错误时非常有用,尤其是在该错误不会在正常情况下发生时。

在客户端应用程序中(例如使用无头架构的 JavaScript),我们可以检查 errors 条目是否存在,并据此决定是处理 GraphQL 响应还是向用户显示错误消息:

/**
 * If the response contains error(s), return a concatenated error message
 *
 * @param {Object} response A response object from the GraphQL server
 * @return {string|null} The error message or nothing
 */
const maybeGetErrorMessage = (response) => {
  if (response.errors && response.errors.length) {
    return sprintf(
      __(`The API produced the following error(s): "%s"`, 'gato-graphql'),
      response.errors.map(error => error.message).join( __('", "') )
    );
  }
  return null;
}
 
const maybeErrorMessage = maybeGetErrorMessage(response);
if (maybeErrorMessage) {
  // Show error to the user
  // ...
} else {
  // Process response
  // ...
}

警告

全局字段 _warn 和指令 @warn 被添加到 GraphQL schema 中,它们会向响应的 warnings 属性中添加条目。

query {
  _warn(message: "Some warning")
  
  posts {
    id
    featuredImage {
      id
      src
    }
    doesNotHaveFeaturedImage: _isNull(value: $__featuredImage)
      @passOnwards(as: "doesNotHaveFeaturedImage")
      @if(condition: $doesNotHaveFeaturedImage)
        @warn(message: "The post does not have a featured image")
  }
}

两者都可以接收参数 data,在警告响应中提供上下文信息。

这些 schema 元素在需要指示 query 已成功执行但出现了意外条件时非常有用。

使用示例

使用不存在的 ID 获取文章时,自然会返回 null。如果需要将此情况视为错误,可以使用指令 @fail

query GetPost($id: ID!) {
  post(by:{id: $id})
    @fail(
      message: "There is no post with the provided ID"
      data: {
        id: $id
      }
    )
  {
    id
    title
  }
}

结合 Multiple Query Execution 扩展,我们可以使用 _fail 获得相同的结果(请注意,当 $postExiststrue 时,FailIfPostNotExists 操作不会被执行):

query GetPost($id: ID!) {
  post(by:{id: $id}) {
    id
    title
  }
  _notNull(value: $__post) @export(as: "postExists")
}
 
query FailIfPostNotExists($id: ID!)
  @skip(if: $postExists)
  @depends(on: "GetPost")
{
  errorMessage: _sprintf(
    string: "There is no post with ID '%s'",
    values: [$id]
  ) @remove
  _fail(
    message: $__errorMessage
    data: {
      id: $id
    }
  ) @remove
}

我们可以使用 _fail 确保指定邮箱的用户尚不存在:

query EnsureUserDoesNotExist($userEmail: Email!) {
  user( by: { email: $userEmail } ) {
    _fail(
      message: "User with given email already exists"
      data: {
        email: $userEmail
      }
    )
  }
}
 
mutation CreateUser($userData: JSONObject!)
  @depends(on: "EnsureUserDoesNotExist")
{
  # ...
}

我们还可以使用 _fail 检查从外部 API 获取数据时是否产生了错误:

query ConnectToExternalGraphQLAPI($endpoint: String!, $query: String!) {
  externalData: _sendGraphQLHTTPRequest(
    input: {
      endpoint: $endpoint
      query: $query
    }
  ) @export(as: "externalData")
  _propertyIsSetInJSONObject(
    object: $__externalData
    by: {
      key: "errors"
    }
  ) @export(as: "endpointHasErrors")
}
 
query FailIfExternalAPIHasErrors($endpoint: String!)
  @include(if: $endpointHasErrors)
  @depends(on: "ConnectToExternalGraphQLAPI")
{
  errorMessage: _sprintf(
    string: "Connecting to endpoint %s produced errors",
    values: [$endpoint]
  ) @remove
  data: _objectProperty(
    object: $externalData,
    by: {
      key: "errors"
    }
  ) @remove
  _fail(
    message: $__errorMessage
    data: {
      endpoint: $endpoint
      endpointData: $__data
    }
  ) @remove
}
 
query GetExternalAPIData
  @skip(if: $endpointHasErrors)
  @depends(on: "ConnectToExternalGraphQLAPI")
{
  data: _objectProperty(
    object: $externalData,
    by: {
      key: "data"
    }
  )
}