2017-04-18 6 views
2

서버에서 GraphQL 및 mongoose를 사용하고 있습니다.Apollo 클라이언트 돌연변이 오류 처리

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

나는에 접근하고 싶습니다 :

유효성 검사 오류가 GraphQL 돌연변이를 발생

는 응답은 다음과 같습니다 클라이언트 측에서 상태 코드 (200)로 응답을 보냅니다 apollo-client mutation promise의 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

'오류'인스턴스를 작성하여'throw' 문을 사용해보십시오 –

답변

1

참고 : 더 최신 버전의 Apollo Client에서 돌연변이 오류가 catch에 나타나므로이 답변 (그리고 틀림없이 전체 질문)이 이제 구식입니다. 돌연변이에서

GraphQL 오류는 현재 then 내부의 반응에 errors 필드에 표시됩니다. 나는 그들이 대신 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

이것은 작동하지 않습니다. 오류는 .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