我正在为我的客户端使用ReactJS和Relay。考虑以下突变:
import {
commitMutation,
graphql
} from 'react-relay';
import environment from '../../../../environment';
const mutation = graphql`
mutation CompanyMutation($company: CompanyInput!) {
createCompany(data: $company) {
id
}
}
`
export const createCompany = (company, callback) => {
console.log(company);
const variables = {
company: company
}
commitMutation(
environment,
{
mutation,
variables,
onCompleted: () => {
callback()
},
onError: (error) => {
throw new Error(error)
},
},
);
}
如何处理从GraphQLServer发送的错误响应:
{
"errors": [
{
"message": "E11000 duplicate key error collection: mom.companies index: name_1 dup key: { : \"TEST
\" }",
"locations": [
{
"line": 4,
"column": 3
}
],
"stack": "WriteError({\"code\":11000,\"index\":0,\"errmsg\":\"E11000 duplicate key error collection: mom.companies index: name_1 dup key: { : \\\"RENATO\\\" }\",\"op\":{\"createdAt\":1509103201877,\"deleted\":false,\"name\":\"TEST\",\"ein\":\"1234\",\"test\":false,\"multiSite\":true,\"siteLimit\":10,\"enabled\":false,\"_id\":\"59f316618ba865186815d3de\",\"__v\":0}})\n at Function.MongoError.create (D:\\9. DEV\\WORKSPACE\\momejected\\node_modules\\mongodb-core\\lib\\error.js:31:11)\n at toError (D:\\9. DEV\\WORKSPACE\\momejected\\node_modules\\mongodb\\lib\\utils.js:139:22)\n at D:\\9. DEV\\WORKSPACE\\momejected\\node_modules\\mongodb\\lib\\collection.js:669:23\n at handleCallback (D:\\9. DEV\\WORKSPACE\\momejected\\node_modules\\mongodb\\lib\\utils.js:120:56)\n at D:\\9. DEV\\WORKSPACE\\momejected\\node_modules\\mongodb\\lib\\bulk\\unordered.js:465:9\n at handleCallback (D:\\9. DEV\\WORKSPACE\\momejected\\node_modules\\mongodb\\lib\\utils.js:120:56)\n at resultHandler (D:\\9. DEV\\WORKSPACE\\momejected\\node_modules\\mongodb\\lib\\bulk\\unordered.js:413:5)\n at D:\\9. DEV\\WORKSPACE\\momejected\\node_modules\\mongodb-core\\lib\\connection\\pool.js:469:18\n at _combinedTickCallback (internal/process/next_tick.js:67:7)\n at process._tickDomainCallback (internal/process/next_tick.js:122:9)",
"path": [
"createCompany"
]
}
],
"data": {
"createCompany": null
}
}
在这种情况下,不会调用onError
。
如何在变异中捕获并处理此返回的错误?
答案 0 :(得分:4)
onCompleted
将在此文档Relay Modern Mutations上返回response
和error
的2个参数
但在我看来,回调函数并不容易处理,所以我只是把它改成Promise就像这样
export const createCompany = (company) =>
new Promise((resolve, reject) => {
const variables = {
company
};
commitMutation(
environment,
{
mutation,
variables,
onCompleted: (resp, err) => {
if (err) return reject(err);
return resolve(resp);
},
onError: (err) => {
return reject(err);
}
}
);
});
如何调用组件
createCompany(company)
.then((resp) => {
// handle your response here..
})
.catch((err) => {
// handle your error here..
})