You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Relay执行CreateUserMutation出现无返回数据错误,如何捕获规避?

How to Catch or Avoid Uncaught Relay Library Errors for Expected Mutation Failures

I'm running a CreateUserMutation with React-Relay. The mutation returning an error (like the email unique constraint violation below) is expected behavior, but my console is throwing an uncaught error from the Relay library:

Uncaught Error: No data returned for operation CreateUserMutation, got error(s): A unique constraint would be violated on User. Details: Field name = email See the error source property for more information. at createError (RelayError.js:44) at Object.create (RelayError.js:29) at normalizePayload (normalizePayload.js:31) at Object.next (RelayModernEnvironment.js:245) at Object.next (RelayObservable.js:223) at Object.next (RelayObservable.js:561) at Object.next (RelayObservable.js:561) at RelayObservable.js:492 at _subscribe (RelayObservable.js:609) at RelayObservable.subscribe (RelayObservable.js:315) at Object.next (RelayObservable.js:376) at Object.next (RelayObservable.js:561) at RelayObservable.js:484

How can I properly catch or prevent this error?


Let's break down why this happens and how to fix it:

This error pops up because Relay expects some data payload back from every mutation—even when there's an expected validation error. If your backend only returns errors without any matching data structure for the mutation's return type, Relay doesn't know how to process it and throws an uncaught exception.

Here are the most effective fixes:

1. Adjust Your Backend to Return Partial Data With Errors

Most GraphQL servers support returning both data and errors in the same response. For your CreateUserMutation, even when the email is duplicated, have your backend send back a minimal payload that matches your mutation's return type (e.g., an empty User object, or the id of the existing user) alongside the error. This tells Relay the operation completed in a format it understands, and you can handle the error in your frontend code.

2. Catch Errors Directly in Your Mutation Execution

Depending on which Relay API you're using, you can explicitly catch errors before they become uncaught:

If using useMutation with mutateAsync:

const [createUser] = useMutation(CreateUserMutation);

async function handleUserCreation(input) {
  try {
    await createUser({ variables: { input } });
    // Handle successful creation
  } catch (error) {
    // Your expected error handling here (e.g., show a user-friendly toast)
    console.log("Validation error:", error.message);
  }
}

If using the older commitMutation API:

commitMutation(environment, {
  mutation: CreateUserMutation,
  variables: { input },
  onError: (error) => {
    // Catch and handle the expected error here
    console.log("Failed to create user:", error.message);
  },
  onCompleted: (response, errors) => {
    // If your backend returns partial data + errors, check here too
    if (errors) {
      console.log("Validation issues:", errors);
    }
  },
});

3. Add a Global Error Handler to Your Relay Environment

You can set up a network layer error handler to catch these Relay-specific errors globally before they hit the console:

const network = Network.create(
  async (operation, variables) => {
    const response = await fetch("/graphql", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ query: operation.text, variables }),
    });
    return response.json();
  },
  {
    onError: (error) => {
      // Catch global Relay errors here
      console.log("Relay error caught:", error.message);
      // Return true to prevent the error from being thrown as uncaught
      return true;
    },
  }
);

const environment = new Environment({
  network,
  store: new Store(new RecordSource()),
});

The core takeaway: Relay needs a data payload to process mutations. If your backend can't return valid data for failed validations, make sure you're explicitly catching errors in your mutation flow to avoid uncaught exceptions.

内容的提问来源于stack exchange,提问作者waqas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:06:39