将GraphQL错误存储为字符串



我有一个登录表单。当点击提交按钮时,我会通过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

这取决于您如何设置一些东西,但是,假设您可以在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);
  }
});

相关内容

最新更新