Home > Enterprise >  SWR NextJS error doesn't get handled after throwing
SWR NextJS error doesn't get handled after throwing

Time:12-11

I am trying to handle the errors that get thrown in my SWR fetcher. Currently whenever I throw an error my app just stops working and I get an "Unhandled Runtime Error".

What I did was just throw the error inside the fetcher. Here is my code:

async function getFetcher(xxx: xxx) {
    const config = {
        params: {
            xxx: xxx
        },
    };

    return axios
        .get(url, config)
        .then((response) => {
            if (response.data.error) {
                console.log("Error");

                throw new Error(response.data.error);
            } else {
                const data = response.data

                return data;
            }
        })
        .catch((error) => {
            console.log("throwing error...");

            throw error;
        });
}

export function useFetcher(xxx: xxx) {
    const { data, error } = useSWR("/integrations/facebook/getAdSpend", (url: string) => getFetcher(xxx), {
        suspense: true,
    });

    if (error) {
        // NEVER GETS TO THIS POINT
        console.log("Error: "   error);
    }

    return {
        data: data,
        isLoadingData: !error && !data,
        error: error,
    };
}

I expected SWR to pick that error up and return it in the error variable. But it never even gets to the point where I can check the error variable, because my app just stops and displays the "Unhandled Runtime Error".

This is what I'm getting: enter image description here

It's my first time working with SWR and errors in that way so I don't really know where to go from here.

Am I throwing it wrong? Why does SWR not handle it as expected?

EDIT:

This way I can catch and handle the error, but it is not passed as the error variable:

export function useFetcher(xxx: xxx) {
    const { data, error } = useSWR("/integrations/facebook/getAdSpend", (url: string) => getFetcher(xxx).catch((error) => {
        // The error thrown in the then block
        console.log(error);
    }), {
        suspense: true,
    });

    if (error) {
        // NEVER GETS TO THIS POINT
        console.log("Error: "   error);
    }

    return {
        data: data,
        isLoadingData: !error && !data,
        error: error,
    };
}

CodePudding user response:

I think the issue is inside the then block of getFetcher

     if (response.data.error) {
         console.log("Error");

         throw new Error(response.data.error);

Why are you throwing error inside the then block? error handle is done inside catch block. if catch block catches an error this error will be passed to the useSwr.

  • Related