apollo-client: How to catch mutation errors from the server
I’ve got a question about error handling client side.
My server returns this on validation error:
{
"data": {
"auth": null
},
"errors": [
{
"message": "An authentication error has occurred",
"name": "AuthenticationError",
"time_thrown": "2017-03-26T01:26:50.439Z",
"data": {
"errors": {
"login": "Authentication failed. Invalid email or password"
}
}
}
]
}
I’d like to get access to the validation errors using apollo-client mutation - something like this:
return auth(values) //<— this is a mutation
.then(({data}) => {
loginThenRedirect(data); // <--- log user in
})
.catch((mutationErrors) => {
const {errors} = mutationErrors.data // <--- doesn't work
this.setState({errors}) // <— display the errors
});
But mutationErrors
get swallowed up and only show a string Error: GraphQL error: An authentication error has occurred…
Is there a way to get the contents of the server error so I can display it client side?
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 23
- Comments: 15 (3 by maintainers)
When I catch the error from a mutation like this,
The following message is logged to the console,
So I got the impression that this issue was still occurring.
When I inspected the object more closely, like this,
It logged an array of error objects.
So the problem was my expectations, not the object itself. Just putting this here for posterity, in case anyone else is caught off-guard by this behaviour.
@helfer Ok that worked out.
I was able to get the error object by doing
const error = JSON.parse(JSON.stringify(mutationError))
not sure if there is a better way to turn the string into an object but this works for me.
Thank you all for the help!
Hope this helps someone: if server returns error code >= 400 then
graphqlErrors
onerror
object is empty, so responses above are not helpful. If you try to read them like @baptistemanson suggested it’s also not gonna work because the body stream was already read from. To get errors in this case you need toerror.networkError.result.errors
.Am experiencing a similar issue with graphql-java backend. Cannot access the errors within the catch.
e.graphQLErrors is undefined.
Maybe its the response sent back by the server? Does anybody know what that data is supposed to look like?
Is it a good idea to catch user-specific errors like “wrong email or password”, using apollo-errors? I’m trying to figure out how to update the store on a catch.
@webular can you try this with
mutationError.graphQLErrors[0].data
?If that doesn’t work, please print
JSON.stringify(mutationError)
and then paste the output here.Thanks!
Got the same, and it doesn’t seem to be documented