You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中Catch块无法捕获Appwrite GraphQL API登录错误求助

问题

使用Web SDK与Appwrite GraphQL API实现用户登录时,输入错误邮箱或密码,API返回200响应,内容如下:

{
    "errors": [
        {
            "message": "Invalid credentials. Please check the email and password.",
            "extensions": {
                "category": "appwrite"
            },
            "locations": [
                {
                    "line": 5,
                    "column": 9
                }
            ],
            "path": [
                "accountCreateEmailSession"
            ]
        }
    ],
    "data": {
        "accountCreateEmailSession": null
    }
}

当前实现代码:

const login = async (email, password) => {
    try {
      const res = await graphql.mutation({
        query: `mutation (
          $email: String!,
          $password: String!,
      ) {
        accountCreateEmailSession(
          email: $email,
          password: $password,
      ) {
          _id
        }
      }`,
        variables: {
          email: email,
          password: password,
        },
      });
      console.log(res);
    } catch (error) {
      console.log(error);
      throw error;
    }
  };

预期错误输入时,错误进入catch块打印日志,但实际在try块中输出响应,需要解决该问题。

解决方法

  • GraphQL API的特性是:即使请求存在业务错误,也会返回200状态码,错误信息会放在响应体的errors数组中,而非触发HTTP层面的错误,所以不会自动进入catch块。
  • 修改代码,在获取响应后手动检查errors字段,若存在则抛出错误:

修改后的代码:

const login = async (email, password) => {
    try {
      const res = await graphql.mutation({
        query: `mutation (
          $email: String!,
          $password: String!,
      ) {
        accountCreateEmailSession(
          email: $email,
          password: $password,
      ) {
          _id
        }
      }`,
        variables: {
          email: email,
          password: password,
        },
      });
      
      // 手动检查GraphQL错误并抛出
      if (res.errors && res.errors.length > 0) {
        throw new Error(res.errors[0].message);
      }
      
      console.log(res);
      return res;
    } catch (error) {
      console.log(error);
      throw error;
    }
  };
  • 这样当存在错误时,会主动抛出Error,进入catch块处理,符合预期逻辑。

内容的提问来源于stack exchange,提问作者r121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:15:25