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
相关产品推荐
相关产品推荐

