graphqlrelayrelaymodern

How can I catch RelayObervable Unhandled error when graphql errors are returned?


My backend is returning the following response:

const errorMessage = {
  errors: [
    {
      message: 'User is logged out',
    },
  ],
  data: null,
};
return res.status(200).json(errorMessage);

My react-native app using relay is returning the following error:

RelayObservable: Unhandled Error Error: 
Relay request for `HomeQuery` failed by the following reasons:

This error shows up when I try to query the backend and it returns the above 'errorMessage' graphql errors array. I have no way of catching this error in my relay network layer BEFORE it throws the redscreen. My Relay Environment looks like this:

const network = new RelayNetworkLayer([
  urlMiddleware({
    url: () => Promise.resolve(`${config.endpoint}backend`),
    headers: async () => authenticateHeaders(fetchHeaders),
  }),
  retryMiddleware({ fetchTimeout: 1000 }),
  next => req => {
    if (!req.uploadbles) {
      req.Accept = 'application/json';
      req['Content-Type'] = 'application/json';
    }

    return next(req);
  },
  next => async req => {
    const res = await next(req);
    if (isLoggedOut(res)) {
      // Using react-navigation, route to the login screen
      dispatch(routeToLogin())
      // I also tried returning `dispatch(routeToLogin())` and `{ data: null, errors: res.payload.errors }` without luck
    }

    return res;
  }
  ]);

Is there a way I can navigate using dispatch(routeToLogin()) without seeing the redscreen error when graphql errors are returned?

Edit 1

For react-relay-network-modern: You can add the noThrow option like so: new RelayNetworkLayer(middlewares, { noThrow: true });

The noThrow option doesn't exist for react-relay-network-layer (relay classic), is there anything I can do to work around it?


Solution

  • Please try noThrow option:

    const network = new RelayNetworkLayer(middlewares, { noThrow: true });