通过 Apollo Server (NestJS) 处理异常

Processing an exception through 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
}

REST 抛出真正的 401 JSON:

{
    "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
}