Query Functions
Query FunctionsYanıt Hata Tetikleyicisi

Yanıt Hata Tetikleyicisi

Included in the “Power Extensions” bundle

GraphQL isteğinin başarısız olmasını tetiklemek için yanıta açıkça bir hata girişi ekler (bir alan beklenen koşulları karşılamadığında).

Açıklama

Bu modül, GraphQL yanıtına eklenecek hataları açıkça tetiklemek ve uyarı eklemek için alanlar ve direktifler ekler.

Hatalar

Yanıttaki errors özelliğine bir giriş ekleyen global alan _fail ve direktif @fail, GraphQL şemasına eklenir.

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

Her ikisi de hata yanıtında bağlamsal bilgi sağlamak için data argümanını da alabilir.

Bu şema öğeleri, böyle bir hata doğal koşullarda gerçekleşmediğinde, çalıştırılan GraphQL queries'inde bir hata olduğunu açıkça belirtmek için kullanışlıdır.

Ardından, istemci tarafındaki uygulamamızda (headless kurulum ile JavaScript gibi), errors girişinin var olup olmadığını kontrol edebilir ve buna göre GraphQL yanıtını işleyebilir ya da kullanıcıya bir hata mesajı gösterebiliriz:

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

Uyarılar

Yanıttaki warnings özelliğine bir giriş ekleyen global alan _warn ve direktif @warn, GraphQL şemasına eklenir:

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

Her ikisi de uyarı yanıtında bağlamsal bilgi sağlamak için data argümanını da alabilir.

Bu şema öğeleri, queries başarıyla çalıştırılmış olsa bile bazı koşulların beklendiği gibi olmadığını belirtmek için kullanışlıdır.

Örnekler

Var olmayan bir ID ile gönderi almak doğal olarak null döndürür. Bu koşulu bir hata olarak ele almamız gerekiyorsa, @fail direktifini kullanabiliriz:

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 uzantısıyla birlikte, _fail kullanarak aynı sonuçları elde edebiliriz ($postExists true olduğunda FailIfPostNotExists operasyonunun çalıştırılmadığına dikkat edin):

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
}

Verilen e-posta adresine sahip kullanıcının henüz mevcut olmadığından emin olmak için _fail kullanabiliriz:

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

Ayrıca harici bir API'den veri alınmasının hata üretip üretmediğini kontrol etmek için _fail kullanabiliriz:

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