javascript - 将 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
解决方案
这取决于你如何设置一些东西,但是,假设你可以state
在你的ShowError
函数中访问:
使用 GraphQL 时,错误可能以两种方式发生: 1. 网络错误,将在.catch
. 要处理此问题,catch
您可以将错误消息存储在状态中,然后从以下位置访问它ShowError
:
...
.catch(err => {
setState({errorMessage: err.message});
});
- 作为错误查询的结果,通常返回带有
errors
数组的成功响应。要处理这种情况,您可以在您的.then
:
...
.then(({data, errors}) => {
if (errors && errors.length) {
setState({errorMessage: errors[0].message});
} else {
localStorage.setItem('token', data.loginEmail.accessToken);
}
});
推荐阅读
- python - 为开发设置沙盒容器环境的好方法是什么?
- python - 解包字典
- python - 如何从 sqlalchemy .execute() 方法中获取价值?Python + Sqlalchemy + MS SQL 服务器
- acumatica - 报表设计器中 Acumatica 中金额字段的文字表示
- python - 如何解决爬取GitHub问题正文时出现非法字符的问题?
- yocto - yocto如何支持ftp命令?
- python - 未找到 Anaconda3 Python shapely 模块
- sql - 在 Postgres (Redshift) 中使用两个选择列运行 MAX 聚合查询时出现问题
- r - 新的 Hugo 帖子未显示 - RMarkdown/Blogdown
- shopify - 如何根据单选按钮选择更改下拉选择?