Apollo Client on React - How to retrieve the error message fomated? - react-apollo

I can't find info about it in anywhere...
Consider this very simple scenario...
<Mutation mutation={LOGIN_MUTATION}>
{(login, { data, loading, error }) => {
if (error) {
console.log(error)
}
I am receiving a string error message like...
Error: GraphQL error: ERROR_INVALID_LOGIN_PROVIDER
at new ApolloError (bundle.umd.js:92)
at MutationData.onMutationCompleted (react-hooks.cjs.js:636)
at react-hooks.cjs.js:559
at tryCallOne (core.js:37)
at core.js:123
at JSTimers.js:289
at _callTimer (JSTimers.js:146)
at _callImmediatesPass (JSTimers.js:194)
at Object.callImmediates (JSTimers.js:458)
at MessageQueue.__callImmediates (MessageQueue.js:366)
I can't take actions based on the error message formated in this way. ERROR_INVALID_LOGIN_PROVIDER could be ERROR_INVALID_PASSWORD, for example...
I need to take decisions based on the error messages. but I just receive a string containing the graphql error, the modules inside the js and a lot of information that's not important. Is there any way to receive the error message formatted imn a way that I can extract only the server error ?

This should be possible
error in your example should be an ApolloError with the possible GraphQLErrors or a NetworkError
(login, { data, loading, error }) => {
if (error) {
if (error.graphQlErrors && error.graphQLErrors.length > 0) {
// There are graphQL errors and there may be multiple but its always an array.
// You should handle it properly
const { message } = error.graphQLErrors[0]
console.log(message) // e.g. ERROR_INVALID_LOGIN_PROVIDER
} else if (error.networkError) {
// There may be a network error
const { message } = error.networkError
console.log(message) // e.g. NetworkError when attempting to fetch resource.
}
}

Related

Terminate a graphql request from Apollo Link

I have an ApolloLink setup for the AWSAppSyncClient in my React project to check if the user is authorized to make the graphql request. If the user is not authorized then, link should not invoke the forward method rather just return an Error for unauthorized access (making it a terminating link).
I tried returning the plain Error response (also tried it with Observable.of), but the request doesn't resolves but keeps on to retry the request on an endless loop.
Need a better solution to implement it.
const authLink = new ApolloLink((operation, forward) => {
const { operationName } = operation;
if (checkIfNotAuthorized(operationName)) {
const error = new Error('Access denied');
return { errors: [error], data: null };
}
return forward(operation);
});

AWS Textract does not run callback in error free run of analyzeDocument

CURRENTLY
I am trying to get AWS Textract working on a Lambda function and am following documentation on https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Textract.html#analyzeDocument-property
My Lambda code:
"use strict";
const AWS = require("aws-sdk");
exports.handler = async (event) => {
let params = JSON.parse(event.body);
console.log("Parse as document...");
let textract = new AWS.Textract();
let doc = params["doc"];
let config = {
Document: {
Bytes: doc,
}
};
textract.analyzeDocument(config, function (err, data) {
console.log("analyzing..."); //<-- nothing logged to console if no error
if (err) {
console.log(err, err.stack);
}
// an error occurred
else {
console.log("data:" + JSON.stringfy(data)); //<-- nothing logged to console if no error
} // successful response
});
console.log("Finished parsing as document.");
};
ISSUE
I cannot get the data back from Textract. It seems I am unable to get the callback working entirely. What's odd is if there is an error e.g. my configuration is wrong, the error handling of the callback will print the log and "analyzing..." log, but without error, none of the logs in the callback print.
Current Logs:
Parse as document...
Finished parsing as document.
Expected / Desired Logs:
Parse as document...
analyzing...
data:{textract output}
Finished parsing as document.
Please help!
NOTES
I am using a role for that Lambda that allows it to access Textract.
I get the same result whether I include the HumanLoopConfig settings or not.
Solved, apparently I needed to setup a promise:
let data = await textract.analyzeDocument(config).promise()
console.log("data:"+data );
console.log("Finished parsing as document.")

(VueJS, Axios) Different way to catch errors

I'm currently building a single page application based on Laravel and VueJS.
Is there any better way then mine to handle errors with axios?
This is how I currently do it when a user clicks on login button:
VueTemplae:
methods : {
authenticateUser() {
axios.post('/api/login', this.form).then(() => {
this.$router.push({name : 'home'});
}).catch((error) => {
this.error = error.response.data.message;
});
}
}
Api route:
public function login() {
try {
// do validation
} catch(Exception) {
// validation failed
throw new Exception('login.failed');
}
// manually authentication
if(Auth::attempt(request()->only('email', 'password'))) {
return response()->json(Auth::user(), 200);
}
// something else went wrong
throw new Exception('login.failed');
}
Unfortunately, throwing an exception always prints an internal server error into the console.
If I return something else than an exception, axios always executes then().
Is there any way to prevent this or a better way to handle axios responses?
Thank you!
Your API needs to return a response with a 4XX status code in order for the catch block to fire in your Vue component.
Example:
After you catch the error on the API side, send a response with status code 400 Bad Request. It will be formatted similarly to your successful login response, but with an error message and 400 status code instead of 200.

The browser overwrites the content of the message after receiving the response

I have a little problem with DingoAPI and Vue.js when I'm trying to get my error message from response. I think the browser is replacing my custom message by the default one. Here is my code:
PHP script
if($request->readerId){
Return succes (this works properly)
else{
return $this->response->error(
'No reader',
400 //(or diffrent code)
);
}
Vue.js script
await axios.post(API_URL + 'card/', {
some data
}, {
headers: {
headers
},
}).then(({data}) => {
context.commit(SET_RESPONSE, data);
}).catch((error) => {
console.log(error.message);
throw error
})
When I'm trying to look on my message in the network tab I can see (so DingoAPI did it correctly):
{"message":"No reader","status_code":400}
But when I'm using console.log(error.message) or trying to show it on the page there is standard error message:
Request failed with status code 400
Is there a way to set error message with DingoAPI and catch it in my .js script?
Maybe I need to write my own custom exception?
What you want is access to the data of the response from your error variable.
console.log(error.response.data.message); // No reader
Otherwise you can log error.response to see the object:
console.log(error.response);
If you wonder why it's printing Request failed with status code 400:
The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.
Source: https://github.com/axios/axios/issues/960#issuecomment-309287911

Parse.Query unable to find objects when called within Parse.Cloud code

I'm struggling to figure out why my queries will not work when called from Parse.Cloud triggers.
I want to define some logic after an object of particular class was saved (the class is 'Message' in my case).
I'm testing the following simple code in my cloud/main.js:
const conversationQuery = new Parse.Query('Conversation');
conversationQuery.get('myIdHere', { useMasterKey: true })
.then(conversation => {
console.log('### Conversation is', conversation);
})
.catch(err => {
console.log('### Error is', err);
});
Parse.Cloud.afterSave('Message', req => {
const conversationQuery1 = new Parse.Query('Conversation');
conversationQuery1.get('myIdHere', { useMasterKey: true })
.then(conversation => {
console.log('>>> Conversation is', conversation);
})
.catch(err => {
console.log('>>> Error is', err);
});
});
And when I start my instance of parse-server, the following is logged to the console:
### Conversation is { myObjectHere }
However, when I save any object of 'Message' class, I get an error:
>>> Error is { Error: Object not found. <stacktrace here>, message: 'Object not found.', code: 101 }
I'd expect it to log the very same object that was retreived when the server started but instead, it returns a '101 object not found' error.
I think I configured everything according to the documentation but there's a possibility I just missed something.
I'm using Parse Server 3.1.3 and Parse JS SDK 2.1.0
https://github.com/parse-community/parse-server#logging it depends on how you start your parse server, but generally something like: VERBOSE="1" parse-server

Resources