Unable to retrieve errors occured in Graphql mutation in flutter project - flutter

I am using the package graphql_flutter for GraphQL operations in my flutter app. The queries and mutations are going well but I cannot retrieve the errors by following the ways mentioned in their doc. Every time I receive a generic error message which is,
ClientException: Failed to connect to http://127.0.0.1:3006/graphql:
That I get by doing,
print(result.exception.toString());
My mutation looks like,
final MutationOptions mutationOptions = MutationOptions(
documentNode: gql(mutationString),
variables: vars
);
final QueryResult result = await _instance._client.mutate(mutationOptions);
if (result.hasException) {
// none of the following prints the expected error.
print(result.exception.clientException.message);
print(result.exception.graphqlErrors);
print(result.exception.toString());
}
print(result.data);
return result.data;
Whereas in the apollo client, My error is :
{
"errors": [
{
"message": "Invalid Phone number provided",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"otp"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
....
But I get none of that.
Note: The success response is coming as expected. I would like to know how can I get the graphql errors.

I found the problem. It is because android cannot connect to 127.0.0.1 or localhost from the emulator. I replaced the host with my local IP address and it is working fine now.

Put this in a try/ catch block and see if it can catch any exceptions
final QueryResult result = await _instance._client.mutate(mutationOptions);

the original question was how to get the graphql errors.
I'm using graphql: ^5.0.0
I checked the docs and found this example:
if (result.hasException) {
if (result.exception.linkException is NetworkException) {
// handle network issues, maybe
}
return Text(result.exception.toString())
}
but that just gave me the exception, not the error, I casted the result exception to the type of error and was able to get the message:
if (result.hasException) {
if (result.exception!.linkException is ServerException) {
ServerException exception =
result.exception!.linkException as ServerException;
var errorMessage = exception.parsedResponse!.errors![0].message;
print(errorMessage);
throw Exception(errorMessage);
}
}
this seems like a lot of work for a simple message, I wonder if there is another simpler built-in way to do it

Related

I want Typeorm to return undefined rather than an error

Hi I want to check if a user is in the database already.
I use Typeorm and Postgres.
I use Typeorm to check if the user is in my DB if not so that's ok and I want the variable to be null/undefined. The issue is that it stops my server with a 400 error code and the process stops.
const isInDb = await this.clientDb.findOne({ email });
error when not found
response: {
statusCode: 400,
message: 'cannot update DB, this request is invalid',
error: 'Bad Request'
},
I'm not familiar with the TypeORM API, but if you want to replace unwanted rejections, you could always wrap the returned promise:
function hideRejection<T>(promise: Promise<T>, rejectValue: T = undefined): Promise<T> {
return promise.catch(() => rejectValue)
}
Then use it like:
const isInDb = await hideRejection(this.clientDb.findOne({ email }));
I just used getcount() query builder to check how many times the row exists. This doesn't throw an error.

How to handle non explicit errors inside sails.js helpers?

I am trying to figure out how the Error handling in Sails.js works. Unfortunatley the code examples in the docs do not cover this use case.
The problem is I keep getting this error:
UsageError: `.intercept()` handler returned `undefined`, but this should never happen.
Regardless, here is a summary of the original underlying error:
Now all I am trying to do is call a helper and if it fails, then I want to catch the error (any), log it and run some code. If I wouldn't be using Sails but normal promises I would have handled it like this:
await helper().catch((err) => { // run some code }
In Sails I should be able to use .intercept() instead of .catch()
My code looks like this:
// ExportController.js
const csv = await sails.helpers.files.convertToCsv(data)
.intercept((err) => {
sails.log.error(err)
req.addFlash('error_messages', 'Error parsing data to csv!')
return res.redirect(`/`);
})
// convert-to-csv.js
if (!Array.isArray(inputs.data)) {
throw new Error('invalid inputs.data type: ' + typeof inputs.data)
};
Now how can I avoid getting this error?
The code examples show only cases where errors that are explicitly added to the exits object are handled, but not for general error handling.
In the docs it says that if the filter argument is
not provided, ALL errors will be intercepted.
Or is that only true for db queries? Because the .intercept() doc section is in that subcategory.
You could use “throw ‘errorCode’;” for example:
Set the exits:
exits {
errorWithCsvFile: {
responseType: 'badRequest'
}
}
const csv = await sails.helpers.files.convertToCsv(data)
.intercept(‘somethingWrongCode’, ‘errorWithCsvFile’)
... // Other handles
.intercept(err => new Error(err))
Alternative:
try {
...
const csv = await sails.helpers.files.convertToCsv(data)
.intercept((err) => {
sails.log.error(err)
req.addFlash('error_messages', 'Error parsing data to csv!')
throw 'badRequest';
})
...
} catch (err) {
sails.log.err(err);
return res.redirect(`/`);
}

API V1 RESTful. I got "Unknown error" when added line break to JSON. Is it OK?

I'm testing API queries and sending POST with such body:
{
"books": "12",
"available": "true",
"id": "qwe2323-2342rfws-23r2rfew"
}
I got 200 response - OK.
But when I add line break to one of the string data, e.g.:
{
"books": "12",
"available": "true",
"id": "qwe2323-2342rfws-23r
2rfew"
}
I got 500 "Unknown error".
My question: Can the server recognize this error and return a response, for example, WRONG_ID? In fact, I just added a line break character to the identifier string. In theory, the script should see the forbidden symbol without problems and return the corresponding error. Can I give such a recommendation to fix this error?
The payload is INVALID which generates an exception at the server and responded with 500 as it cannot understand the data payload.
To check the payload and show a INVALID JSON DATA or through any custom message, you can check the payload on every POST request at the server side, as in below example for PHP programming language:
private function handleRequest(Request $request, Programmer $programmer)
{
// ...
if ($data === null) {
throw new \Exception(sprintf('Invalid JSON: '.$request->getContent());
}
// ...
}
Reference:
https://knpuniversity.com/screencast/rest/error-invalid-json#handling-invalid-json

Need one help regarding fetching data value from response

Need one help regarding fetching data value from response.
Below is my response which I got after hitting URL.
{
"response": {
"Error Message": "Invalid Input missing",
"success": "false""
}
}
In this I want to read "Error Message" through POSTMAN test. For same reason I have written below code, but it is not working due to space between key.
var data = JSON.parse(responseBody);
tests ["Verify Error message"] = data.response.Error Message==="Invalid Input - Mandatory data(Company ID/source Id/SalesRep Ids/ContactPerson Ids) missing";
You're trying to use Error Message as a field with a space in it. Try:
tests ["Verify Error message"] = data.response.["Error Message"]==="Invalid Input - Mandatory data(Company ID/source Id/SalesRep Ids/ContactPerson Ids) missing";
This is not good to compare string.
In your response you must have like this,
{
"response": {
"Error Message": "Invalid Input missing",
"success": "false",
"responseCode" : 400
}
}
for more response codes, please go to this link,
http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
Then after do comparison,
var data = JSON.parse(responseBody);
if(data.reponse.responseCode == '400'){
// do stuff
}

Prediction request end up with "invalid data" errors

I get errors when posting prediction requests, but when posting the same requests from the online interface (from Google's API reference page) works well.
I have also posted a new issue on the Git repository, but it seems that no-one even looks at these issues. How lame of Google !!
Well I am posting predict request, which look like this:
var parameters = {
auth: jwtClient,
project: googleProjectID,
id: 'interest_classifier',
input: {
csvInstance: ["country united states", "/location/location"]
}
};
return prediction.trainedmodels.predict(parameters, function(err, response) {
if (err) {
logger.info(null, "prediction err ", err);
}
logger.info(null, "response from predict ", response);
return callback(null, response);
});
And I get this:
err { [Error: Input data invalid.]
code: 400,
errors:
[ { domain: 'global',
reason: 'invalidValue',
message: 'Input data invalid.' } ] }
To clarify: my trained model contains a value and two textual features.
Again, when running this from the online tool (client side) it works well, only when I run it from my node.js server, does it fail.
What's up with that? Anyone knows?
Could this be some encoding issue? request headers?
EDIT:
this is how i authenticate :
var jwtClient = new google.auth.JWT('*****#developer.gserviceaccount.com', 'keys/key.pem', null, ['https://www.googleapis.com/auth/prediction']);
jwtClient.authorize(function(err, tokens) {
logger.info(null, "authorizing");
if (err) {
logger.info(null, "error ", err);
} else {
return logger.info(null, "authenticated ", tokens);
}
});
OK,
So I've dug into Google's code and found out an important detail that is not properly documented.
I think this might be relevant to other people using this library, not only the ones who use google predict.
So most requests need to include a project id in the parameters, but in some cases you also need to include post data (like in my case).
I was trying to include this post data directly in the parameters like so :
var parameters = {
auth: jwtClient,
project: googleProjectID,
id: 'interest_classifier',
input: {
csvInstance: ["country united states", "/location/location"]
}
};
Now I found (this is not documented !!) that the whole part which belongs to the post data should be included within a "resource" field, like this:
var parameters = {
auth: jwtClient,
project: googleProjectID,
id: 'interest_classifier',
resource:{
input: {
csvInstance: ["country united states", "/location/location"]
}
}
};
I believe this will be relevant to any request which includes post data.
Cheers,
Ilan