【问题标题】:Store GraphQL errors as String将 GraphQL 错误存储为字符串
【发布时间】:2020-06-20 01:37:28
【问题描述】:

我有一个登录表单。当点击提交按钮时,我通过 GraphQL 后端检查电子邮件和密码是否正确。如果是,则返回一个令牌并将其存储在本地存储中。有时会出现错误,例如:

“密码错误”或“用户不存在”。

有什么方法可以将这些错误存储为字符串,以便稍后使用条件渲染显示它们?

这就是我的突变的样子:

function submitForm(LoginMutation: any) {
    const { email, password } = state;
    if(email && password){
      LoginMutation({
        variables: {
            email: email,
            password: password,
        },
    }).then(({ data }: any) => {
      localStorage.setItem('token', data.loginEmail.accessToken);
    })
    .catch(console.log)
    }
  }

我在退货时就这样使用它

 return (
      <Mutation mutation={LoginMutation}>
        {(LoginMutation: any) => (
        ....)}>
       </Mutation>
)

目前,我只是根据令牌是否存在显示一个错误,但我想让我的错误特定于 GraphQL 错误。

function ShowError(){
  if (!localStorage.getItem('token'))
  {
    console.log('Login Not Successful');
    return <Typography color='primary'>Login Not Successful</Typography>

  }
}

编辑:

示例错误:

[Log] Error: GraphQL error: Key (email)=(c@c.com) already exists.

我试过了,但它从来没有记录任何东西:

.then(({data, errors}:any) => {
        if (errors && errors.length) {
          console.log('Errors', errors);
          setErrorMessage(errors[0].message);
          console.log('Whats the error', errors[0].message)
        } else {
          console.log('ID: ', data.createUser.id);
        }
      })
    ```
The backend isn't made by me


【问题讨论】:

    标签: javascript reactjs typescript graphql apollo


    【解决方案1】:

    这取决于您如何设置一些东西,但是,假设您可以在 ShowError 函数中访问 state

    使用 GraphQL 时,错误可能以两种方式发生: 1. 网络错误,将在.catch 中捕获。为了处理这个问题,你可以在你的catch 中存储错误消息的状态,然后从ShowError 访问它:

    ...
    .catch(err => {
      setState({errorMessage: err.message});
    });
    
    1. 作为错误查询的结果,通常返回带有errors 数组的成功响应。要处理这种情况,您可以在 .then 中添加错误检查:
    ...
    .then(({data, errors}) => {
      if (errors && errors.length) {
        setState({errorMessage: errors[0].message});
      } else {
        localStorage.setItem('token', data.loginEmail.accessToken);
      }
    });
    

    【讨论】:

    • 你能看看更新的qs吗?我试过 2. 但它对我不起作用。没有任何记录
    • 如果您不控制后端,他们可能会将错误作为网络错误返回。您是否尝试在捕获中添加很多内容?您在哪里看到添加的日志(示例错误)?
    • *加日志,不加很多
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 2010-10-20
    • 1970-01-01
    • 2022-12-12
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多