gpt4 book ai didi

node.js - 当响应源自微服务时,GraphQL如何处理错误消息

转载 作者:行者123 更新时间:2023-12-03 08:10:29 24 4
gpt4 key购买 nike

我有一个API,当传入无效的授权 token 时,它会像这样响应:

未经授权的回复:

{
"status": "failure",
"message": "Unauthorized"
}

但是,当传入有效 token 时,它将以对象数组作为响应,每个对象都代表一个文档,如下所示:

授权回复:
[{
"_id": "5bd8f520e68ba2003ec9f528",
"user": "5bd8f50cced689002769d254",
"title": "A title for a document",
"content": "Some content for a document",
}, {
"_id": "5bd8f520e68ba2003ec9f528",
"user": "5bd8f50cced689002769d254",
....
}]

How do i gracefully handle error responses in GraphQL when they originate from my microservices running express? and how do i cover the change in data structure within the response?



我的解析器:
const getDocuments = async context => {
const config = {
headers: {
Authorization: context.token
}
};

try {
return await axios
.get("http://document_service:4000/v1/documents", config)
.then(response => {
return response.data;
})
.catch(error => {
return error.data;
});
} catch (err) {
return err;
}
};

const Query = {
docServiceGetDocs: (obj, args, context) => getDocuments(context)
};

response.data 将返回文档数组或带有状态和消息的对象。

我的架构:
type getDocuments {
_id: String
user: String
title: String
content: String
}

type Query {
docServiceGetDocs: [getDocuments]
}

[getDocuments] 我想这需要一个对象数组,但是不确定如果我得到未经授权的响应作为对象,该如何处理。

我正在使用apollo服务器2

最佳答案

理想情况下,如果内容响应用于传达错误而不是状态代码,则无论状态如何,API的响应都将具有某种程度的一致性。

{
"status": "failure",
"message": "Unauthorized",
"response": []
}

{
"status": "success",
"message": "",
"response": [{ user: "Dan" }],
}

但是,如果这不容易解决,则只需检查解析器中响应的形状即可:
const getDocuments = async context => {
const config = {
headers: {
Authorization: context.token
}
};

try {
const response = await axios.get("http://document_service:4000/v1/documents", config)
const data = response.data
if (data && data.status === 'failure') {
throw new Error(data.message)
}
return data
} catch (err) {
// example of how to handle axios errors

let message = ''
if (err.response) {
// Status code out of the range of 2xx, format error message according
} else if (err.request) {
// The request was made but no response was received, format message accordingly
} else {
message = err.message
}
// throw whatever error you have so it's included in your graphql response
throw new Error(message)
}
};

关于node.js - 当响应源自微服务时,GraphQL如何处理错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53089562/

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