gpt4 book ai didi

node.js - 通过 Apollo Server (NestJS) 处理异常

转载 作者:行者123 更新时间:2023-12-03 12:18:42 27 4
gpt4 key购买 nike

有没有办法通过 apollo 异常处理程序手动运行异常?

我在 GraphQL 中有 90% 的应用程序,但仍然有两个模块作为 REST,我想统一处理异常的方式。

所以 GQL 查询抛出标准 200 错误数组,其中包含消息、扩展等。

{
"errors": [
{
"message": { "statusCode": 401, "error": "Unauthorized" },
"locations": [{ "line": 2, "column": 3 }],
"path": [ "users" ],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"response": { "statusCode": 401, "error": "Unauthorized" },
"status": 401,
"message": { "statusCode": 401, "error": "Unauthorized" }
}
}
}
],
"data": null
}

REST 使用 JSON 抛出真正的 401:
{
"statusCode": 401,
"error": "Unauthorized"
}

那么我可以简单地捕获并包装 吗? Apollo 服务器格式的异常 还是我必须手动格式化我的 REST 错误?谢谢

我正在使用 NestJS 和 GraphQL 模块。

最佳答案

您可以设置自定义exception filter它捕获 REST-Api 错误并将它们包装为 Apollo Server 格式。就像是:

@Catch(RestApiError)
export class RestApiErrorFilter implements ExceptionFilter {
catch(exception: RestApiError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = 200;
response
.status(status)
.json(RestApiErrorFilter.getApolloServerFormatError(exception);
}

private static getApolloServerFormatError(exception: RestApiErrorFilter) {
return {}; // do your conversion here
}

关于node.js - 通过 Apollo Server (NestJS) 处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61864912/

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