logaretm / villus

🏎 A tiny and fast GraphQL client for Vue.js

Home Page:https://villus.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Possible to return Promise.reject on plugin?

Laurensvdmaas opened this issue · comments

Hi,

Is there a possibility to return Promise.reject inside a plugin? I've seen some global error handling with sentry but not sure how to reject the promise within the plugin.

I would like to handle errors with:

 try {
    await execute(vars);
  } catch (e) {
    // handle error.
  }

instead of:

const {error} = await execute(vars)
if(error) // handle error

Thank you!

Possible but not recommended as you might cause value skipping setting the reactive values on the useMutation returns, which could be acceptable if the only way you use useMutation is via the execute function.

So the dirty way is to introduce a custom fetch plugin that throws, something similar to fetch default plugin which you can use as a baseline but make sure to throw the error. I'm not going to offer code guidance there since I don't like recommending this hack.

Another way that I recommend, is to compose useMutation with a custom one:

export function useThrowingMutation(query) {
  const mutation = useMutation(query);

  mutation.execute = function executeWithThrow(...args) {
     const { data, errors } = await execute(...args);
     if (error) {
       throw error;
    }

    return { data };
  }
}

This is simpler and should work well and you can use it for all of your mutations.

Internally this is hard to offer out of the box because villus uses a pipeline of plugins system, so if one crashes it is a big deal and causes integrity concerns to the GraphQL result.

I understand, thanks for your answer!