问题
I have configured and set up a fully functional express-nextjs-graphql-apollo app that can login/logout a user, and perfectly do CRUD. The last and very important step is to display error messages on client-side.
So far, I'm only getting this red error in a console: POST http://localhost:3000/graphql 500 (Internal Server Error)
For example, a login form validation. When no input is provided, it's supposed to get an invalid input error message, or E-Mail is invalid
if email format is incorrect.
The following mutation code tested in graphql localhost:3000/graphql
:
mutation {
login(userInput: {email:"" password:""}){
userId
}
}
returns the message below. And I actually want this message to be displayed on client.
{
"errors": [
{
"message": "Please provide input.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"login"
]
}
],
"data": null
}
I also tried displaying error messages on client inside Mutation component with onError:
onError={error => {
console.log("ERROR in SigninBox component ", error);
}}
Which only shows this error message in a console: Response not successful: Received status code 500
This is how I setup up the 'express-graphql'
package on my server:
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 resolver:
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 };
}
Client-side:
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);
I also tried this onError check:
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}`);
}}
That basically returned the same error message: [Network error]: ServerError: Response not successful: Received status code 500
My goal is to show the message that I would normally get in graphql localhost:3000/graphql
which comes from my resolver, eg: E-Mail is invalid
, Please provide input.
or etc.
How do I get this message
to be sent to the client onError handler?
回答1:
After doing some research I realized that the error itself is an object
onError={error => {
console.log("ERROR in SigninBox ", { error });
}}
And the error message is stored inside error.networkError.result.errors[0].message
来源:https://stackoverflow.com/questions/56195999/apollo-client-doesnt-display-an-error-message