kun*_*ajs 6 exception node.js graphql apollo-server nestjs
有没有办法通过 apollo 异常处理程序手动运行异常?
我 90% 的应用程序都在 GraphQL 中,但仍然有两个 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
}
Run Code Online (Sandbox Code Playgroud)
其中 REST 使用 JSON 抛出真正的 401:
{
"statusCode": 401,
"error": "Unauthorized"
}
Run Code Online (Sandbox Code Playgroud)
那么我可以简单地捕获异常并以 Apollo Server 格式包装异常,还是必须手动格式化 REST 错误?谢谢
我正在使用 NestJS 和 GraphQL 模块。
您可以设置自定义异常过滤器来捕获 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
}
Run Code Online (Sandbox Code Playgroud)