Search code examples
reactjsreduxerror-handlingrtk-query

Why does the query error appear in the console even after it has been handled? RTK Query + React


This is my error handler :

export const onAuthQueryStartedErrorToast = async (
  _: any,
  { queryFulfilled }: any,
) => {
  try {
    await queryFulfilled;
  } catch (error) {
    const isError = error as AuthErrorType;

    if (isError.error.data) {
      toast.warn(defineMessage(isError.error.data.message));
    } else {
      toast.warn("some error occured");
    }
  }
};

And this is my endpoint and the query I want to handle

export const AuthService = baseApi.injectEndpoints({
  endpoints: (builder) => {
    return {
      authMe: builder.query<AuthMeResponseType, void>({
        query: () => ({
          url: "v1/auth/me",
          method: "GET",
        }),
        onQueryStarted: onAuthQueryStartedErrorToast,
        providesTags: ["Auth"],
      }), ... }

And the error handling works just as expected, I get the toast with the message, however the console error 401 is still there and I have no idea how to get rid of it. Seems like it logs the error into the console before the handler(if it makes sense). Any ideas, please?


Solution

  • As far as I am aware of this is default browser behavior for network errors to be logged to the console and there is nothing you can do from your web page/application to change or prevent this. Seeing these logs doesn't necessarily mean something wasn't properly handled within the app.

    What you can do, however, is to change in the console what you actually see. In other words, you can "filter" errors from the console.

    In the browser's devtools you can change the logging level to remove errors from the logged output.

    Examples:

    • Chrome: Deselect "Verbose" which displays all output, and deselect "Errors" to not output error logs.

      enter image description here

    • Safari: Select anything but "All" or any multi-select that includes "Errors".

      enter image description here

    Other browsers should have similar settings.

    Note: Changing these settings only affects your browser. Users of your page/app can, and will, still be able to configure their browser how they like and see the browser-generated logging.

    Note also that this will hide all errors generated by the page, not just network errors, so be aware of this during development that you may need to reenable error logging later to see important information. Use at your discretion.