レスポンスエラートリガー
GraphQLリクエストの失敗を引き起こすために、レスポンスにエラーエントリを明示的に追加します(フィールドが期待される条件を満たさない場合)。
説明
このモジュールは、エラーを明示的にトリガーし、GraphQLレスポンスに警告を追加するためのフィールドとディレクティブを追加します。
エラー
グローバルフィールド _fail とディレクティブ @fail がGraphQLスキーマに追加されます。これらはレスポンスの 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 を受け取ることができ、エラーレスポンスにコンテキスト情報を提供できます。
これらのスキーマ要素は、実行されたGraphQLクエリにエラーがあることを明示的に示す際に有用です。特に、そのエラーが自然な状況では発生しない場合に役立ちます。
クライアント側のアプリケーション(ヘッドレス構成の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スキーマに追加されます。これらはレスポンスの 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 を受け取ることができ、警告レスポンスにコンテキスト情報を提供できます。
これらのスキーマ要素は、クエリが正常に実行されたにもかかわらず、予期しない条件が発生したことを示す際に有用です。
使用例
存在しない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 を使って同様の結果を得ることができます($postExists が true の場合、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")
{
# ...
}また、外部APIからデータを取得した際にエラーが発生したかどうかを確認するために _fail を使用することもできます。
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"
}
)
}