2017-04-18 52 views
2

我在服務器上使用GraphQL和貓鼬。阿波羅客戶端突變錯誤處理

當驗證錯誤發生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

嘗試使用'throw'語句創建'Error'實例 –

回答

1

注意:這個答案(可以說是整個問題)現在已經過時了,因爲在更新版本的Apollo客戶端中,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客戶端的API更改之前發佈的。 – stubailo

1

似乎從@stubailo以前的答案並不涵蓋所有用例。如果我在服務器端代碼上發生錯誤,則響應代碼將不同於200,並且將使用.catch()而不是使用.then()來處理錯誤。

Link到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