错误
模拟 GraphQL 错误响应。
你可以通过在响应对象中包含 error
键来模拟 GraphQL 错误响应。确保你模拟的错误响应符合 GraphQL 规范 规范,以便你的客户端能够按预期处理它们。
¥You can mock a GraphQL error response by including the error
key in the response object. Make sure your mocked error responses abide by the GraphQL specification so your client can process them as expected.
请求错误
¥Request errors
仅包含 errors
键而没有 data
键的响应通常表示 请求错误。
¥A response that only contains the errors
key and no data
usually indicates a request error.
api.query<User>('GetUser', () => {
return HttpResponse.json({
errors: [
{
message: 'Simulated client error',
},
],
})
})
字段错误
¥Field errors
模拟 字段错误 时,请确保将 locations
和 path
属性与错误 message
属性一起包含,以形成正确的字段错误响应。你也可以将字段错误与部分响应组合在一起。
¥When mocking field errors, make sure to include the locations
and path
property alongside the error message
to form a correct field error response. You can combine field errors with partial responses, too.
api.query<User, { id: string }>('GetUser', ({ variables }) => {
return HttpResponse.json({
errors: [
{
message: `Name for user with ID ${variables.id} could not be fetched.`,
locations: [{ line: 4, column: 5 }],
path: ['user', 'name'],
},
],
data: {
user: {
id: variables.id,
},
},
})
})
你还可以在模拟错误中包含
extensions
属性。¥You can also include the
extensions
property in your mocked errors.
上面的请求处理程序使用部分数据(user.id
)响应 GetUser
查询,并因缺少字段 user.name
而返回错误。它从查询本身派生出 locations
和 path
:
¥The request handler above responds to the GetUser
query with partial data (user.id
) and returns an error for the missing field user.name
. It derives its locations
and path
from the query itself:
query GetUser {
user {
id
name
}
}