Search code examples
graphqlrelayjsrelayrelaymodernreact-relay

Catch errors from usePreloadedQuery


I have this code and I want to catch the errors that happens in the query used by usePaginationFragment. what happens now is when something goes wrong in the backend, the data.queryName returns null, and there is no way to know about the errors. the question is how can I receive the errors when happend?

function MyPagination(){
  return (
    <ErrorBoundary>
      <Suspense fallback={"loading..."} >
        <PaginationLoadable
          preloadedQuery={preloadedQuery}
          query={graphql`...`}
        />
      </Suspense>
    </ErrorBoundary>
  )
}

function PaginationLoadable(this: never, props: PaginationLoadableProps){

    const preloadedData = usePreloadedQuery<any>(props.query, props.preloadedQuery);

    const {data} = usePaginationFragment(
        props.fragment,
        preloadedData
    );

    console.log(data[ /*queryName*/ ] === null)

}

Thank you


Solution

  • Here is how I did it, it must throw an error in the NetworkLayer function like so:

    
    new Environment({
      network: Network.create(
        function fetch(operation, variables) {
          return (
            Axios
            .post(
              '*API_NEDPOINT*',
              {
                query: operation.text,
                variables
              }
            )
            .then(
              response => {
                if(response.data.errors){
                  const er: any = new Error('ServerError');
                  er.data = response.data.data;
                  er.errors = response.data.errors;
                  return Promise.reject(er);
                }
                return response.data;
              }
            )
          );
        }
      ),
      store
    });