gpt4 book ai didi

reactjs - Apollo 客户端不显示错误信息

转载 作者:行者123 更新时间:2023-12-03 07:40:12 31 4
gpt4 key购买 nike

我已经配置并设置了一个功能齐全的 express-nextjs-graphql-apollo 应用程序,它可以登录/注销用户,并且完美地执行 CRUD。最后也是非常重要的一步是在客户端显示错误消息。

到目前为止,我只在控制台中收到此红色错误:POST http://localhost:3000/graphql 500(内部服务器错误)

例如,登录表单验证。当没有提供输入时,它应该得到一个无效的输入错误消息,或者如果电子邮件格式不正确,则 E-Mail is invalid

以下变异代码在 graphql localhost:3000/graphql 中测试:

mutation {
login(userInput: {email:"" password:""}){
userId
}
}

返回下面的消息。我实际上希望这条消息显示在客户端上。

{
"errors": [
{
"message": "Please provide input.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"login"
]
}
],
"data": null
}

我还尝试在带有 onError 的 Mutation 组件内的客户端上显示错误消息:

    onError={error => {
console.log("ERROR in SigninBox component ", error);
}}

仅在控制台中显示此错误消息:Response not successful: Received status code 500

这就是我在服务器上设置 'express-graphql' 包的方式:

  server.use(
"/graphql",
graphqlHTTP({
schema: graphQlSchema,
rootValue: graphQlResolvers,
graphiql: true,
customFormatErrorFn(err) {
if (!err.originalError) {
return err;
}
const data = err.originalError.data;
const message = err.message || "An error occurred.";
const code = err.originalError.code || 500;
return {
message: message,
status: code,
data: data
};
}
})
);

登录解析器:

  login: async ({ userInput }) => {
if (
validator.isEmpty(userInput.email) ||
validator.isEmpty(userInput.password)
) {
throw new Error("Please provide input.");
}

if (!validator.isEmail(userInput.email)) {
throw new Error("E-Mail is invalid.");
}
if (
validator.isEmpty(userInput.password) ||
!validator.isLength(userInput.password, { min: 5 })
) {
throw new Error("Password too short!");
}

const user = await User.findOne({ email: userInput.email });
if (!user) {
const error = new Error("User does not exist!");
error.code = 404;
throw error;
}
const isEqual = await bcrypt.compare(userInput.password, user.password);
if (!isEqual) {
throw new Error("Password is incorrect!");
}
const token = jwt.sign(
{ userId: user.id, email: user.email },
"somesupersecretkey",
{
expiresIn: 1000
}
);
return { userId: user.id, token: token, tokenExpiration: 1 };
}

客户端:

import { Mutation, withApollo } from "react-apollo";
import gql from "graphql-tag";
import redirect from "../lib/redirect";
import { setCookie } from "../helpers/cookie";

const SIGN_IN = gql`
mutation login($email: String!, $password: String!) {
login(userInput: { email: $email, password: $password }) {
token
}
}
`;

const Signin = ({ client }) => {
let email, password;

return (
<Mutation
mutation={SIGN_IN}
onCompleted={data => {
setCookie("token", data.login.token);
client.cache.reset().then(() => {
redirect({}, "/admin");
});
}}
onError={error => {
console.log("ERROR in SigninBox ", error);
}}
>
{(login, { data, error }) => (
<div>
<form
onSubmit={e => {
e.preventDefault();
e.stopPropagation();
login({
variables: {
email: email.value,
password: password.value
}
});
email.value = password.value = "";
}}
>
<div>
<h1>Admin Page Login</h1>
</div>
<div className="form-label-group">
<input
className={`form-control ${error ? "is-invalid" : ""}`}
name="email"
id="inputEmail"
placeholder="Email"
ref={node => {
email = node;
}}
/>
<label htmlFor="inputEmail">Email address</label>
{error && (
<div className="invalid-feedback">
No user found with that information.
</div>
)}
</div>

<div>
<input
name="password"
id="inputPassword"
placeholder="Password"
ref={node => {
password = node;
}}
type="password"
/>
<label htmlFor="inputPassword">Password</label>
</div>
<button type="submit">Login</button>
</form>
</div>
)}
</Mutation>
);
};
export default withApollo(SignIn);

我也试过这个 onError 检查:

onError={({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
if (networkError) console.log(`[Network error]: ${networkError}`);
}}

基本上返回了相同的错误消息:[网络错误]: ServerError: 响应不成功: 收到状态代码 500

我的目标是显示我通常会在 graphql localhost:3000/graphql 中收到的来 self 的解析器的消息,例如:E-Mail is invalid请提供输入。 或等等。如何将此消息发送到客户端 onError 处理程序?

最佳答案

经过一些研究我意识到错误本身是一个对象

onError={error => {
console.log("ERROR in SigninBox ", { error });
}}

错误信息存储在error.networkError.result.errors[0].message

enter image description here

关于reactjs - Apollo 客户端不显示错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56195999/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com