如何在接口返回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;
redux-toolkit 成员 @phryneas 在 stackoverflow 上的回答: