2017-04-18 6 views
2

私はサーバー上でGraphQLとmongooseを使用しています。Apolloクライアントの突然変異のエラー処理

検証エラーがGraphQL変異は、クライアント側ではステータスコード200で応答を送信する応答は次のようになります発生します。

{ 
 
    "data": null, 
 
    "errors": [{ 
 
    "message": "error for id...", 
 
    "path": "_id" 
 
    }] 
 
}

私はへのアクセスを取得したいと思いますapollo-client突然変異の約束のcatch機能を使用した検証エラーです。ような何か:

 this.props.deleteProduct(this.state.selectedProductId).then(response => { 
 
     // handle successful mutation 
 
     }).catch(response => { 
 
     const errors = response.errors; // does not work 
 
     this.setState({ errorMessages: errors.map(error => error.message) }); 
 
     });

はどのようにこれを行うことができますか?

+0

「エラー」インスタンス –

答えて

1

注:最近のApollo Clientのバージョンでは、catchに突然変異のエラーが表示されているため、この回答は(おそらくは質問全体が)時代遅れになっています。

thenの応答内のerrorsフィールドに、現在のところ変異からのGraphQLエラーが表示されます。私は、彼らが代わりにcatchに表示すべきであると判断する主張は間違いなくあると思うが、ここではGitHuntから突然変異の抜粋です:

// The container 
const withData = graphql(SUBMIT_REPOSITORY_MUTATION, { 
    props: ({ mutate }) => ({ 
    submit: repoFullName => mutate({ 
     variables: { repoFullName }, 
    }), 
    }), 
}); 

// Where it's called 
return submit(repoFullName).then((res) => { 
    if (!res.errors) { 
    browserHistory.push('/feed/new'); 
    } else { 
    this.setState({ errors: res.errors }); 
    } 
}); 
+0

を作成して 'throw'文を試してみてください。これは動作しません。エラーは.catch()で処理され、.then()では処理されません。 – tgdn

+0

このコメントは、Apollo ClientでAPIを変更する前に投稿されています。 – stubailo

1

@stubailoから以前の答えは、すべてのユースケースをカバーしていないようです。サーバ側のコードにエラーが発生した場合、レスポンスコードは200と異なり、エラーは.catch()を使用して処理され、.then()は使用されません。

Link to GitHub。

.then().catch()の両方のエラーを処理するのが最適です。

const { deleteProduct } = this.props; 
const { selectedProductId } = this.state; 

deleteProduct(selectedProductId) 
    .then(res => { 
     if (!res.errors) { 
      // handle success 
     } else { 
      // handle errors with status code 200 
     } 
    }) 
    .catch(e => { 
     // GraphQL errors can be extracted here 
     if (e.graphQLErrors) { 
      // reduce to get message 
      _.reduce(
      e.graphQLErrors, 
      (res, err) => [...res, error.message], 
      [] 
     ); 
     } 
    }) 
+1

なぜエラーメッセージとエラーコードを抽出するためのより優雅な方法がないのだろうか。 – Theson

関連する問題