简体   繁体   English

如何处理突变 GraphQL 错误而不是 Apollo onError()

[英]How to handle mutation GraphQL error instead of Apollo onError()

Server side, I am throwing a 403 Forbidden, to manage access to an API call.服务器端,我抛出一个 403 Forbidden,以管理对 API 调用的访问。

To catch the GraphQL error for a mutation, I've tried the following: (method #1 is working when catching errors for useQuery() )为了捕获突变的 GraphQL 错误,我尝试了以下方法:(方法 #1 在捕获useQuery()错误时有效)

const [m, { error }] = useMutation(MY_MUTATION);

if(error) {
    console.error('Error return #1');
}

try {
  await m({
    variables,
    onError: (e: ApolloError) => {
       console.error('Error return #2');
    }
  }).catch(e) {
     console.error('Error return #3');
  };
} catch (e) {
    console.error('Error return #4');
}

Instead, from my Apollo onError() , the following GraphQL errors are returned and the execution stops.相反,从我的 Apollo onError()返回以下 GraphQL 错误并停止执行。 It does not go into any of my mutation error handling attempts:它不会 go 进入我的任何突变错误处理尝试:

graphQLErrors:, Array [
  Object {
    "extensions": Object {
      "code": "FORBIDDEN",
      "response": Object {
        "error": "Forbidden",
        "message": "Access is denied.",
        "statusCode": 403,
      },
    },
    "message": "Access is denied.",
  },
]

If a similar GraphQL error is returned from useQuery() , it shows it using:如果从useQuery()返回类似的 GraphQL 错误,则显示它使用:

const { data, error, loading } = useQuery( MY_QUERY );

if(error) {
    console.error('Error return #1');
}

Based on useMutation documentation I believe mutate (or m ) function doesn't accept onError callback and you have to set it in useMutation options.基于useMutation 文档,我相信mutate (或m ) function 不接受onError回调,你必须在useMutation选项中设置它。

const [m, { error }] = useMutation(MY_MUTATION, {
  onError: (e: ApolloError) => {
     console.error('Error return #2');
  }
});

if (error) {
    console.error('Error return #1');
}

try {
  await m({
    variables
  })
} catch (e) {
    console.error('Error return #4');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM