首页 > 解决方案 > 通过 Apollo Server (NestJS) 处理异常

问题描述

有没有办法通过 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 Server 格式包装异常,还是必须手动格式化我的 REST 错误?谢谢

我正在使用 NestJS 和 GraphQL 模块。

标签: node.jsexceptiongraphqlnestjsapollo-server

解决方案


您可以设置一个自定义异常过滤器来捕获 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
}

推荐阅读