Query Functions
Query FunctionsAttivatore di Errori nella Risposta

Attivatore di Errori nella Risposta

Included in the “Power Extensions” bundle

Aggiunge esplicitamente una voce di errore alla risposta per provocare il fallimento della richiesta GraphQL (ogni volta che un campo non soddisfa le condizioni previste).

Descrizione

Questo modulo aggiunge campi e direttive per attivare esplicitamente errori, e aggiungere avvisi, che verranno inclusi nella risposta GraphQL.

Errori

Il campo globale _fail e la direttiva @fail, che aggiungono una voce alla proprietà errors nella risposta, vengono aggiunti allo 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"
    )
  }
}

Entrambi possono anche ricevere l'argomento data, per fornire informazioni contestuali nella risposta di errore.

Questi elementi dello schema sono utili per indicare esplicitamente che si è verificato un errore nella query GraphQL eseguita, quando tale errore non si verifica in circostanze naturali.

Successivamente, nella nostra applicazione lato client (come JavaScript con una configurazione headless), possiamo verificare se la voce errors esiste e, in base a ciò, elaborare la risposta GraphQL o mostrare un messaggio di errore all'utente:

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

Avvisi

Il campo globale _warn e la direttiva @warn, che aggiungono una voce alla proprietà warnings nella risposta, vengono aggiunti allo 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")
  }
}

Entrambi possono anche ricevere l'argomento data, per fornire informazioni contestuali nella risposta di avviso.

Questi elementi dello schema sono utili per indicare che, anche se la query è stata eseguita con successo, una condizione non era quella prevista.

Esempi

Recuperare un articolo con un ID inesistente restituirà naturalmente null. Se dobbiamo trattare questa condizione come un errore, possiamo utilizzare la direttiva @fail:

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

In combinazione con l'estensione Multiple Query Execution, possiamo ottenere gli stessi risultati utilizzando _fail (si noti che l'operazione FailIfPostNotExists non viene eseguita quando $postExists è true):

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
}

Possiamo utilizzare _fail per assicurarci che l'utente con l'indirizzo e-mail fornito non esista ancora:

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

Possiamo anche utilizzare _fail per verificare se il recupero dei dati da un'API esterna ha prodotto errori:

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