Hàm Queries
Hàm QueriesKích Hoạt Lỗi trong Phản Hồi

Kích Hoạt Lỗi trong Phản Hồi

Included in the “Power Extensions” bundle

Thêm rõ ràng một mục lỗi vào phản hồi để kích hoạt sự thất bại của yêu cầu GraphQL (khi một trường không đáp ứng các điều kiện mong đợi).

Mô tả

Module này thêm các trường và chỉ thị để kích hoạt lỗi một cách rõ ràng, và thêm cảnh báo, vào phản hồi GraphQL.

Lỗi

Trường toàn cục _fail và chỉ thị @fail, thêm một mục vào thuộc tính errors trong phản hồi, được thêm vào schema GraphQL.

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"
    )
  }
}

Cả hai đều có thể nhận thêm đối số data, để cung cấp thông tin ngữ cảnh trong phản hồi lỗi.

Các phần tử schema này hữu ích để chỉ ra rõ ràng rằng có lỗi trong GraphQL query đã thực thi, khi lỗi đó không xảy ra trong hoàn cảnh bình thường.

Sau đó, trong ứng dụng phía client của chúng ta (chẳng hạn như JavaScript với thiết lập headless), chúng ta có thể kiểm tra xem mục errors có tồn tại hay không và, dựa trên đó, xử lý phản hồi GraphQL hoặc hiển thị thông báo lỗi cho người dùng:

/**
 * 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
  // ...
}

Cảnh báo

Trường toàn cục _warn và chỉ thị @warn, thêm một mục vào thuộc tính warnings trong phản hồi, được thêm vào schema GraphQL:

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")
  }
}

Cả hai đều có thể nhận thêm đối số data, để cung cấp thông tin ngữ cảnh trong phản hồi cảnh báo.

Các phần tử schema này hữu ích để chỉ ra rằng, mặc dù query đã thực thi thành công, một điều kiện nào đó không như mong đợi.

Ví dụ

Truy xuất một bài viết với ID không tồn tại sẽ tự nhiên trả về null. Nếu chúng ta cần xử lý điều kiện này như một lỗi, chúng ta có thể sử dụng chỉ thị @fail:

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

Kết hợp với tiện ích mở rộng Multiple Query Execution, chúng ta có thể đạt được kết quả tương tự bằng cách sử dụng _fail (lưu ý rằng thao tác FailIfPostNotExists không được thực thi khi $postExiststrue):

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
}

Chúng ta có thể sử dụng _fail để đảm bảo rằng người dùng với email đã cho chưa tồn tại:

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")
{
  # ...
}

Chúng ta cũng có thể sử dụng _fail để kiểm tra xem việc truy xuất dữ liệu từ một API bên ngoài có tạo ra lỗi hay không:

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"
    }
  )
}