I am getting an error when I request. Оn the backend side there is a check that the name length is at least 3 characters. The response from the server is correct. but when I try to display an error, the message comes out saying that the answer was not found.
async saveBoard(id, index) {
await this.API.put("/boards/" + id, {
name: this.boards[index].name,
})
.then((response) => {
alert(response.data.message);
this.boards[index].etitable = !this.boards[index].etitable;
})
.catch((error) => {
console.log(error);
});
},
when I try to output error.response.date to the console, I get an error that response is not defined.
How can I solve this problem, why does axios not see the response from the server and the error code?
Error code must be in your catch You can't reach error message in then.
You are probably see error in your console right now
return response;
},
error => {
if (error.response.status == 401 || error.response.status == 419) {
const token = localStorage.getItem('token');
if (token) {
localStorage.removeItem('token');
}
const user = localStorage.getItem('user');
if (user) {
localStorage.removeItem('user');
}
router.push('/login');
} else {
if (error.response.status == 403) {
router.push('/');
}
}
return Promise.reject(error);
});```
I added a return to the interceptors function. Problem solved thanks for your help.
Related
I have aproblem when test Apollo.When I try query with apollo and graphql, i want response return error and partical data, so I set property errorPolicy:'all'. But its not work. I don't no why? Help please!
Here my code:
query { animal {
name
age }, school {
name
numberfd } } `
const { loading,data,error} = useQuery(GET_DASHBOARD_DATA, {
errorPolicy:'all',
onCompleted: (res) => {console.log("complete",res)},
onError : (res,data) => {console.log("ERRRR",res,data)},
})
and i want to receive:
{
error:[...], data:[animal:[...]] }
but its only response error.Here is Apollo's doc: https://www.apollographql.com/docs/react/data/error-handling/
onError type is onError?: (error: ApolloError) => void;. You don't have data inside onError callback.
After useQuery you can add:
console.log('data', data)
console.log('error', error)
I faced the same issue with errorPolicy: 'all', I only received the partial result inside onCompleted callback of useQuery, but no errors.
I created an ErrorLink like this:
private createErrorLink = () => {
return new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
// filter out errors you don't want to display
const errors = filterSomeErrors(response.errors);
if (errors && response?.data) {
response.data.errors = errors;
}
return response;
});
});
};
Now inside my onCompleted callback I get my data as well as errors. You will have to tweak your types a bit, because seems there is no errors field on response.data by default.
Mind that if you use onError from Apollo and return something from the link, it will retry your request containing errors!
[Error][1]
Hi Team,
Whenever I am receiving the error return from laravel the nuxt.js project displays the error on the page instead the HTML/Forms. How can i handle this.
Here is my php code
return response()->json([
'errors' => [
'email' => ['Sorry we cant find you with those details.'],
],
], 422);
Javascript
async submit() {
await this.$auth.loginWith("local", {
data: this.form
})
In your JavaScript you need to wrap your await promise inside a try catch block. Here's a fix for your JS.
try {
await this.$auth.loginWith("local", {
data: this.form
})
} catch (e) {
return;
}
This is an old question at this point, but I thought I'd post the full code since I was pretty stumped and didn't find many great answers out there:
async handleSubmit() {
try {
const authResponse = await this.$auth.loginWith('local', {
data: this.formData
});
const { status, data } = authResponse;
if (status === 200)
this.createFlashAlert({ 'success': 'Login successful' });
} catch (error) {
if (error.response.status === 422)
this.createFlashAlert(error.response.data);
}
}
So the checklist:
Wrap the login call in a try/catch if you're using async await syntax (be sure to make it an async function i.e. async handleSubmit.
in the catch block, use the error.response object, this is an axios thing. With this you'll be able to access the response status and data.
If you log just the error object, it's not obvious that you can access the response within that error which is what had me stumped.
My backend is returning the following response:
const errorMessage = {
errors: [
{
message: 'User is logged out',
},
],
data: null,
};
return res.status(200).json(errorMessage);
My react-native app using relay is returning the following error:
RelayObservable: Unhandled Error Error:
Relay request for `HomeQuery` failed by the following reasons:
This error shows up when I try to query the backend and it returns the above 'errorMessage' graphql errors array. I have no way of catching this error in my relay network layer BEFORE it throws the redscreen. My Relay Environment looks like this:
const network = new RelayNetworkLayer([
urlMiddleware({
url: () => Promise.resolve(`${config.endpoint}backend`),
headers: async () => authenticateHeaders(fetchHeaders),
}),
retryMiddleware({ fetchTimeout: 1000 }),
next => req => {
if (!req.uploadbles) {
req.Accept = 'application/json';
req['Content-Type'] = 'application/json';
}
return next(req);
},
next => async req => {
const res = await next(req);
if (isLoggedOut(res)) {
// Using react-navigation, route to the login screen
dispatch(routeToLogin())
// I also tried returning `dispatch(routeToLogin())` and `{ data: null, errors: res.payload.errors }` without luck
}
return res;
}
]);
Is there a way I can navigate using dispatch(routeToLogin()) without seeing the redscreen error when graphql errors are returned?
Edit 1
For react-relay-network-modern: You can add the noThrow option like so: new RelayNetworkLayer(middlewares, { noThrow: true });
The noThrow option doesn't exist for react-relay-network-layer (relay classic), is there anything I can do to work around it?
Please try noThrow option:
const network = new RelayNetworkLayer(middlewares, { noThrow: true });
I am trying to do customize messaging with GraphQLError.
There are few use cases that I want to handle with GraphQL Error:
when username and password did not match, I want to return customize the message that username and password did not match.
When the user entered an invalid email, I want to return customize the message that entered email is not valid.
And few other use cases.
I created a ValidateError.js File to use GraphQLError handling function:
const { GraphQLError } = require('graphql');
module.exports = class ValidationError extends GraphQLError {
constructor(errors) {
super('The request is invalid');
var err = errors.reduce((result, error) => {
if (Object.prototype.hasOwnProperty.call(result, error.key)) {
result[error.key].push(error.message);
} else {
result[error.key] = [error.message];
}
return result;
}, {});
}
}
Here is the code of my application index file app.js:
app.use('/graphql', graphqlExpress(req => ({
schema,
context: {
user: req.user
},
formatError(err) {
return {
message: err.message,
code: err.originalError && err.originalError.code,
locations: err.locations,
path: err.path
};
}
})));
My question is how can I use this function for grabbing graphQLError
formatError
Thanks in advance.
"apollo-server-express": "^1.3.5"
"graphql": "^0.13.2"
Just throw your error in resolver, formatError function will catch each error thrown in resolver.
Here is my work:
appError.js
class AppError extends Error {
constructor(opts) {
super(opts.msg);
this.code = opts.code;
}
}
exports.AppError = AppError;
throw an custom error in resolver:
throw new AppError({ msg: 'authorization failed', code: 1001 });
catch this error in formatError:
formatError: error => {
const { code, message } = error.originalError;
return { code, message };
},
Other sample:
throw your error in resolver:
const resolvers = {
Query: {
books: () => {
throw new GraphQLError('something bad happened');
}
}
};
catch error in formatError:
graphqlExpress(req => {
return {
schema,
formatError: err => {
console.log('format error');
return err;
}
};
})
Here is the output:
format error
GraphQLError: something bad happened
at books (/Users/ldu020/workspace/apollo-server-express-starter/src/graphql-error/index.js:23:13)
at /Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql-tools/dist/schemaGenerator.js:518:26
at resolveFieldValueOrError (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:531:18)
at resolveField (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:495:16)
at /Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:364:18
at Array.reduce (<anonymous>)
at executeFields (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:361:42)
at executeOperation (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:289:122)
at executeImpl (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:154:14)
at Object.execute (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/execution/execute.js:131:229)
Inside of GraphQLError you should have access to GraphQLErrorExtensions which should allow you to append your custom messages when throwing errors.
This answer was written with knowledge of apollo server throwing custom errors through this extensions option. This may be achievable but more complex. I suggest checking out apollo server error: https://github.com/apollographql/apollo-server/blob/main/packages/apollo-server-errors/src/index.ts
It looks like what you can do is just pass any additional information through the extensions, but you will only be able to set it inside the constructor: new GraphQLError('your error message', null, null, null, null, null, {"message1": [ "custom message1" ], "message2": [ "customer message1", "custom message2" ]})
I'm using GraphQL and mongoose on the server.
When a validation error occurs the GraphQL mutation sends a response with status code 200. On the client side the response looks like this:
{
"data": null,
"errors": [{
"message": "error for id...",
"path": "_id"
}]
}
I would like to get access to the validation error using the catch functionality of the apollo-client mutation promise. Something like:
this.props.deleteProduct(this.state.selectedProductId).then(response => {
// handle successful mutation
}).catch(response => {
const errors = response.errors; // does not work
this.setState({ errorMessages: errors.map(error => error.message) });
});
How can this be done?
The previous answer from #stubailo does not seem to cover all use cases. If I throw an error on my server side code the response code will be different than 200 and the error will be handled using .catch() and not using .then().
Link to the issue on GitHub.
The best is probably to handle the error on both .then() and .catch().
const { deleteProduct } = this.props;
const { selectedProductId } = this.state;
deleteProduct(selectedProductId)
.then(res => {
if (!res.errors) {
// handle success
} else {
// handle errors with status code 200
}
})
.catch(e => {
// GraphQL errors can be extracted here
if (e.graphQLErrors) {
// reduce to get message
_.reduce(
e.graphQLErrors,
(res, err) => [...res, error.message],
[]
);
}
})
Note: This answer (and arguably the whole question) is now outdated, since mutation errors show up in catch in more recent versions of Apollo Client.
GraphQL errors from the mutation currently show up in the errors field on the response inside then. I think there's definitely a claim to be made that they should show up in the catch instead, but here's a snippet of a mutation from GitHunt:
// The container
const withData = graphql(SUBMIT_REPOSITORY_MUTATION, {
props: ({ mutate }) => ({
submit: repoFullName => mutate({
variables: { repoFullName },
}),
}),
});
// Where it's called
return submit(repoFullName).then((res) => {
if (!res.errors) {
browserHistory.push('/feed/new');
} else {
this.setState({ errors: res.errors });
}
});
Using graphql tag notation, yo have access to errors:
<Mutation mutation={UPDATE_TODO} key={id}>
{(updateTodo, { loading, error }) => (
<div>
<p>{type}</p>
<form
onSubmit={e => {
e.preventDefault();
updateTodo({ variables: { id, type: input.value } });
input.value = "";
}}
>
<input
ref={node => {
input = node;
}}
/>
<button type="submit">Update Todo</button>
</form>
{loading && <p>Loading...</p>}
{error && <p>Error :( Please try again</p>}
</div>
)}
</Mutation>
https://www.apollographql.com/docs/react/essentials/mutations.html