gpt4 book ai didi

reactjs - 如何在 Redux-toolkit rtk-query graphql 应用程序中处理错误格式

转载 作者:行者123 更新时间:2023-12-05 01:52:02 29 4
gpt4 key购买 nike

我正在开发一个基于 redux-toolkit rtk-query 和 graphql 的应用程序。我使用 graphql-codegen 从 graphql 模式开始生成缩减器,一切都按预期工作。

现在我有一个问题来处理错误。我是否了解 redux-toolkit 以这样的特定格式引发自定义错误

{
name: "Error",
message: "System error",
stack:
'Error: System error: {"response":{"errors":[{"message":"System error","locations":[{"line":3,"column":3}],"path":["completaAttivita"],"extensions":{"errorCode":505,"classification":"VALIDATION","errorMessage":"Messaggio di errore","verboseErrorMessage":"it.cmrc.sid.backend.exception.CustomException: I riferimenti contabili non sono più validi","causedBy":"No Cause!"}}],"data":{"completaAttivita":null},"status":200,"headers":{"map":{"content-length":"398","content-type":"application/json"}}},"request":{"query":"\\n mutation completaAttivita($taskName: TipoAttivita, $taskId: String, $determinaId: BigInteger, $revisione: Boolean, $nota: NotaInputInput, $avanzaStatoDetermina: Boolean, $attribuzioniOrizzontali: AttribuzioniOrizzontaliInputInput, $firmaInput: FirmaInputInput, $roles: [String]) {\\n completaAttivita(\\n taskName: $taskName\\n taskId: $taskId\\n determinaId: $determinaId\\n revisione: $revisione\\n nota: $nota\\n avanzaStatoDetermina: $avanzaStatoDetermina\\n attribuzioniOrizzontali: $attribuzioniOrizzontali\\n firmaInput: $firmaInput\\n roles: $roles\\n ) {\\n id\\n }\\n}\\n ","variables":{"taskId":"24ac495b-46ca-42f4-9be2-fd92f0398114","determinaId":1342,"taskName":"firmaDirigente","firmaInput":{"username":"fdfs","password":"fdsf","otp":"fdsdf"}}}}\n at eval (webpack-internal:///../../node_modules/graphql-request/dist/index.js:354:31)\n at step (webpack-internal:///../../node_modules/graphql-request/dist/index.js:63:23)\n at Object.eval [as next] (webpack-internal:///../../node_modules/graphql-request/dist/index.js:44:53)\n at fulfilled (webpack-internal:///../../node_modules/graphql-request/dist/index.js:35:58)'
};

但是我的 graphql 端点返回这个

{
errors: [
{
message: "System error",
locations: [{ line: 3, column: 3 }],
path: ["completaAttivita"],
extensions: {
errorCode: 505,
classification: "VALIDATION",
errorMessage: "Messaggio di errore",
verboseErrorMessage:
"it.cmrc.sid.backend.exception.CustomException: Messaggio di errore",
causedBy: "No Cause!"
}
}
],
data: { completaAttivita: null }
};

使用 rtk-query 和自动生成的客户端我无法访问来自服务器的完整响应。我需要在异常对象中提取错误消息。

从 redix-toolkit 文档中我了解到我需要捕获错误并从 createAsyncThunk 调用 rejectwithvalue() 但我不知道这样做。

这里是基本的 api 对象

import { createApi } from '@reduxjs/toolkit/query/react';
import { graphqlRequestBaseQuery } from './base-request';
import { GraphQLClient } from 'graphql-request';
import { getSession } from 'next-auth/react';

export const client = new GraphQLClient(
`${process.env.NEXT_PUBLIC_API_URL}/graphql`,
{
credentials: 'same-origin',
headers: {
Accept: 'application/json'
}
}
);

export const api = createApi({
baseQuery: graphqlRequestBaseQuery({
client,
prepareHeaders: async (headers, { getState }) => {
const session = await getSession();
if (session) {
headers.set('Authorization', `Bearer ${session?.access_token}`);
}

return headers;
}
}),
endpoints: () => ({}),
refetchOnMountOrArgChange: true
});

最佳答案

感谢@phry 合并我的解决方案。

@rtk-query/graphql-request-base-query(版本 > 2.1.0)引入了一种新的配置来处理错误格式。这里有一个小的解释。

Typization


graphqlRequestBaseQuery<CustomErrorFormat>

Custom Error handler

...
customErrors: (props: ClientError) => CustomErrorFormat
...

Full example https://codesandbox.io/s/headless-microservice-uzujqb?file=/src/App.tsx

import { createApi } from '@reduxjs/toolkit/query/react';
import { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query';
import { ClientError, GraphQLClient } from 'graphql-request';
import { getSession } from 'next-auth/react';

export const client = new GraphQLClient(
`${process.env.NEXT_PUBLIC_API_URL}/graphql`,
{
credentials: 'same-origin',
headers: {
Accept: 'application/json'
}
}
);

export const api = createApi({
baseQuery: graphqlRequestBaseQuery<
Partial<ClientError & { errorCode: number }>
>({
client,
prepareHeaders: async (headers, { getState }) => {
const session = await getSession();
if (session) {
headers.set('Authorization', `Bearer ${session?.access_token}`);
}

return headers;
},
customErrors: ({ name, stack, response }) => {
const { errorMessage = '', errorCode = 500 } = response?.errors?.length
? response?.errors[0]?.extensions
: {};

return {
name,
message: errorMessage,
errorCode,
stack
};
}
}),
endpoints: () => ({}),
refetchOnMountOrArgChange: true
});

关于reactjs - 如何在 Redux-toolkit rtk-query graphql 应用程序中处理错误格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71828943/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com