我正在尝试使用服务器上的Express + Mongoose和客户端上的React + Apollo从Rest API迁移到GraphQL。
async resolve(_, { email, password, passwordConfirmation }) { // Sign Up mutation
const user = new User({ email });
user.password = password;
user.passwordConfirmation = passwordConfirmation;
try{
const createdUser = await user.save();
return createdUser;
} catch(error) {
console.log(error); // Returns errors object like {email: {message: 'E-mail is required'}}
throw new Error(error); // But on the client there is a string with all errors
}
}`
如何处理客户端上的整个错误对象?
答案 0 :(得分:4)
当您进行突变时,Apollo客户端会返回一个承诺。来自该承诺的错误可以在突变的结果承诺的catch块中访问。请参阅下面的示例。
如果我的登录变异有错误,我将在返回的promise的catch块中访问它们,然后将这些错误设置为组件中的本地状态。从那里可以呈现错误(如果存在),或者甚至可以传递给要呈现的子组件(如果您愿意)。请注意,错误通常以数组形式返回。
class LoginForm extends Component {
constructor(props) {
super(props);
this.state = { errors: [] };
}
onSubmit({ email, password }) {
this.props.mutate({
variables: { email, password },
refetchQueries: [{ query }]
}).catch(res => {
const errors = res.graphQLErrors.map(error => error.message);
this.setState({ errors });
});
}
render() {
return (
<div>
<AuthForm
errors={this.state.errors}
onSubmit={this.onSubmit.bind(this)}
/>
</div>
);
}
}
export default graphql(query)(
graphql(mutation)(LoginForm)
);
答案 1 :(得分:0)
您还可以在react-apollo中使用 renderProps ,它会向您提供错误并在第二个参数中的对象中加载状态。
import React, { Component } from 'react';
import { Mutation } from 'react-apollo';
import gql from 'graphql-tag';
import Error from './ErrorMessage';
const LOGIN_MUTATION = gql`
mutation LOGIN_MUTATION($email: String!, $password: String!) {
signin(email: $email, password: $password) {
id
email
name
}
}
`;
class Login extends Component {
state = {
name: '',
password: '',
email: '',
};
saveToState = e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
return (
<Mutation
mutation={LOGIN_MUTATION}
variables={this.state}
>
{(login, { error, loading }) => (
<form
method="post"
onSubmit={async e => {
e.preventDefault();
await login();
this.setState({ name: '', email: '', password: '' });
}}
>
<fieldset disabled={loading}>
<h2>Sign into your account</h2>
<Error error={error} />
<label htmlFor="email">
Email
<input
type="email"
name="email"
placeholder="email"
value={this.state.email}
onChange={this.saveToState}
/>
</label>
<label htmlFor="password">
Password
<input
type="password"
name="password"
placeholder="password"
value={this.state.password}
onChange={this.saveToState}
/>
</label>
<button type="submit">Sign In!</button>
</fieldset>
</form>
)}
</Mutation>
);
}
}
export default Login;