RTK Query 如何让 createApi 的 mutation 抛出错误?

rtk-query/overview

如何在接口返回code !== 000000后,让接口的promise对象进入catch

getCCYPairPriceList({ clientId })
  .catch(() => {
    // 如何进入这里
    debugger
  });

..
baseQuery.js

import { fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react';
import type { BaseQueryFn, FetchArgs, FetchBaseQueryError } from '@reduxjs/toolkit/query';
import { RootState } from '../app/store';

const baseQueryWithRetry = retry(
    fetchBaseQuery({
        baseUrl: process.env.REACT_APP_BASE_URL,
        prepareHeaders: (headers, { getState }) => {
            const accessToken = (getState() as RootState).app.accessToken;
            if (accessToken) {
                headers.set('authorization', `Bearer ${accessToken}`);
            }
            headers.set('Content-Type', 'application/json');
            return headers;
        },
    }),
    { maxRetries: 6 }
);

export const baseQueryWithReauth: BaseQueryFn<
    {
        url: string;
        method?: string | undefined;
        body?: any;
        params?: any;
    } | FetchArgs,
    unknown,
    FetchBaseQueryError
> = async (args, api, extraOptions) => {
    try {
        const result = await baseQueryWithRetry(args, api, extraOptions) as { data: { RES: string } };
        if (result.data.RES) {
            const { body } = JSON.parse(decryptedByAES(result.data.RES));
            switch (body.code) {
                case '000000':
                    return { ...result, data: body }
                default:
                    debugger
                    throw new Error('body.message');
                    // return { ...result, data: body }
            }
        }
        return result;
    }
    catch (err: any) {
        debugger
        // throw new Error('body.message');
        return Promise.reject(err);
    }
}

..
services.js

import { createApi } from '@reduxjs/toolkit/query/react';
import { baseQueryWithReauth } from './baseQuery';

export const quoteApi = createApi({
    reducerPath: 'quoteApi',
    baseQuery: baseQueryWithReauth,
    endpoints: (builder) => ({
        getCCYPairPriceList: builder.mutation<any, object>({
            query: (body) => ({
                url: 'getCCYPairPriceList',
                method: 'POST',
                body,
            }),
        }),
    }),
    refetchOnReconnect: true,
});

export const { useGetCCYPairPriceListMutation } = quoteApi;
阅读 2.7k
1 个回答

redux-toolkit 成员 @phryneas 在 stackoverflow 上的回答:

This is so that your application is not littered with uncaught async exceptions if you are not interested in the result.

You can unwrap the result to get to "throwing" behaviour:

getList({ id }).unwrap().catch(() => { How to get here });

That said, it is very likely that getList should be a query, not a mutation. Mutations are things that change data on your server.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题