Apollo 客户端不显示错误信息
Apollo client doesn't display an error message
我已经配置并设置了一个功能齐全的 express-nextjs-graphql-apollo 应用程序,可以 login/logout 一个用户,并且完美地进行 CRUD。
最后也是非常重要的一步是在客户端显示错误消息。
到目前为止,我只在控制台中收到此红色错误:POST http://localhost:3000/graphql 500 (Internal Server Error)
例如,登录表单验证。当没有提供输入时,它应该会收到无效的输入错误消息,或者 E-Mail is invalid
如果电子邮件格式不正确。
在 graphql localhost:3000/graphql
中测试了以下变异代码:
mutation {
login(userInput: {email:"" password:""}){
userId
}
}
returns下面的留言。我实际上希望这条消息显示在客户端上。
{
"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}`);
}}
那基本上返回了相同的错误信息:[Network error]: ServerError: Response not successful: Received status code 500
我的目标是显示我通常会在 graphql localhost:3000/graphql
中收到的来自我的解析器的消息,例如:E-Mail is invalid
、Please provide input.
等。
如何将此 message
发送到客户端 onError 处理程序?
经过一些研究,我意识到错误本身是一个对象
onError={error => {
console.log("ERROR in SigninBox ", { error });
}}
并且错误信息存储在error.networkError.result.errors[0].message
里面
我已经配置并设置了一个功能齐全的 express-nextjs-graphql-apollo 应用程序,可以 login/logout 一个用户,并且完美地进行 CRUD。 最后也是非常重要的一步是在客户端显示错误消息。
到目前为止,我只在控制台中收到此红色错误:POST http://localhost:3000/graphql 500 (Internal Server Error)
例如,登录表单验证。当没有提供输入时,它应该会收到无效的输入错误消息,或者 E-Mail is invalid
如果电子邮件格式不正确。
在 graphql localhost:3000/graphql
中测试了以下变异代码:
mutation {
login(userInput: {email:"" password:""}){
userId
}
}
returns下面的留言。我实际上希望这条消息显示在客户端上。
{
"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}`);
}}
那基本上返回了相同的错误信息:[Network error]: ServerError: Response not successful: Received status code 500
我的目标是显示我通常会在 graphql localhost:3000/graphql
中收到的来自我的解析器的消息,例如:E-Mail is invalid
、Please provide input.
等。
如何将此 message
发送到客户端 onError 处理程序?
经过一些研究,我意识到错误本身是一个对象
onError={error => {
console.log("ERROR in SigninBox ", { error });
}}
并且错误信息存储在error.networkError.result.errors[0].message