I have a Xamarin.Forms application, which uses Xamarin.Essentials and Plugin.Permissions plugin.
permissionStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
In UWP, It throws an Exception
"Server execution failed".
Any ideas what can cause it, and how this can be solved?
According to your code, I guess that you want to request and check location permission, if yes, you can take a look the following code to request location permission.
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
if(await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
{
await DisplayAlert("Need location", "Gunna need that location", "OK");
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
status = results[Permission.Location];
}
if (status == PermissionStatus.Granted)
{
var results = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));
LabelGeolocation.Text = "Lat: " + results.Latitude + " Long: " + results.Longitude;
}
else if(status != PermissionStatus.Unknown)
{
await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
}
}
catch (Exception ex)
{
LabelGeolocation.Text = "Error: " + ex;
}
Please check Location in package.appxmanifest before.
Related
already use http, Uri parse......
login working, get addresses not work
Here you go to use dio for network call:
try {
_dio.options.contentType = Headers.jsonContentType;
Response response = await _dio.post(
baseUrl + '/verify-otp',
data: {"activation_token": ""}
);
return response;
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
return error;
}
Okay. I've been using Flutter for a little more than a year now. I've been using this same code in almost every app, and it works. For some reason, it doesn't work in this new app that I'm building.
String testString(DocumentSnapshot doc, String val) {
try {
if (doc == null) {
return "error! DB not found!";
}
if (doc[val] == null) {
return "'" + val + "' doesn't exist in DB";
}
return doc[val];
} catch (e) {
return "Error: something went wrong";
}
}
I've also tried this:
String testUndString(DocumentSnapshot doc, String val) {
try {
return doc != null ? (doc[val] != null ? doc[val] : "undefined") : "undefined";
} catch (e) {
return "Error: something went wrong";
}
}
and this:
String testUndString(DocumentSnapshot doc, String val) {
try {
return doc.data != null ? (doc[val] != null ? doc[val] : "undefined") : "undefined";
} catch (e) {
return "Error: something went wrong";
}
}
After doing some searching, it looks like I've done this correctly, but it still returns the error:
NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null.)
Try this code:
if (doc is !DocumentSnapshot) {
return "error! DB not found!";
}
When trying to make a call to a Cloud Function I get a "CloudFunctionsException"
The code of the exception is "INTERNAL
The message is "Response is not valid JSON object."
Describe the bug
To Reproduce
Steps to reproduce the behavior:
- My call from the application is
HttpsCallable _getName;
_getName = CloudFunctions.instance.getHttpsCallable(functionName: 'getName',);
try {
HttpsCallableResult resp = await _getName.call(<String, dynamic>{'name': name,});
Scaffold.of(context).showSnackBar(SnackBar(content: Text("${resp.data}")));
} on CloudFunctionsException catch (e) {
showErrorMessage(context, 'Cloud functions exception with code: ${e.code}, and Details: ${e.details}, with message: ${e.message} ');
} catch (e) {
showErrorMessage(context, e.toString());
}
My Cloud Function is written as so:
exports.getName = functions.https.onCall((data, context) => {
return {
"data" : "You hit the call at least!"
};
});
Expected behavior
In my response, I should get back the data: "You hit the test call". Instead, I get the error
Additional context
When I make calls to the same function but with the HTTP package and receive it on the back end with "onRequest", it works.
void _checkPersonsNameGET(String name)async{
try {
http.Response resp = await http.get(_cloudFunctionUrl,, );
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("${resp.body}", style: TextStyle(color: Colors.green))));
} catch (e) {
showErrorMessage(context, e.toString());
}
}
void _checkPersonsNamePOST(String name)async{
try {
http.Response resp = await http.post(_cloudFunctionUrl, body: { "name" : name } );
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("${resp.body}", style: TextStyle(color: Colors.green))));
} catch (e) {
showErrorMessage(context, e.toString());
}
}
exports.getName = functions.https.onRequest((request, response) => {
const name = request.query.name || request.body.name;
switch (name) {
case 'Andrew':
request.query.name ? response.send("Na he is the boi Q!") : response.send("Na he is the boi B!");
break;
case 'Brett':
request.query.name ? response.send("Na just wierd! Q") : response.send("Na just wierd! B");
break;
case 'Eddie':
request.query.name ? response.send("My brother but yeah! Q") : response.send("My brother but yeah! B");
break;
case 'James':
request.query.name ? response.send("The biggest! Q") : response.send("The biggest! B");
break;
default:
request.query.name ? response.send("Dunno who that is! Q") : response.send("Dunno who that is! B");
break;
}
});
It's a mock application and can be seen here
https://github.com/earyzhe/firebase_cloud_functions_play
In my case, the cloud function was in a file that was not exported in the index file. Make sure your function is properly exported and has been deployed properly.
I have a method and it throws an error so I can catch it in my event and display it to the user, like this:
Meteor.methods({
addPlayer: function(nickname) {
if (nickname == "") {
throw new Meteor.Error('empty-nickname', 'You must choose a nickname');
} else {
Player.insert({
nickname: nickname,
});
}
},
})
and in my event
'submit form': function (e) {
e.preventDefault();
var nickname = $('input').val();
Meteor.call('addPlayer', nickname, function(error, result) {
if (error) {
console.log(typeof error);
console.log(error);
}
});
}
However, meteor still throws an Exception while simulating the effect of invoking 'addPlayer', and the error variable is not an error object, but a string with the same message as the console log, so I get two errors in my console instead of an error object.
Wrapping method.call in a try/catch does not work.
What am I missing here?
-- Edit
Here is an print screen of the result:
Image link for full resolution: http://i.stack.imgur.com/zABar.png
Throw the error only on the server. Wrap it inside if(!this.isSimulation) {}
Meteor.methods({
addPlayer: function(nickname) {
if (nickname == "") {
if(!this.isSimulation) {
throw new Meteor.Error('empty-nickname', 'You must choose a nickname');
}
} else {
Player.insert({
nickname: nickname,
});
}
},
})
I'm hoping to be able to customise the error objects that are passed to the client if an exception occurs on the server.
I'm using the 'then' function on the client to handle success and failure:
hub.server.login(username, password).then(function(result) {
// use 'result'
}, function(error) {
// use 'error'
});
If the login succeeds, 'result' is the return value of the Login method on the server. If the login fails, I throw an exception of 'CustomException'. This is an exception with a 'Code' property.
if (!IsValidLogin(username, password))
throw new CustomException { Code: "BADLOGIN", Message: "Invalid login details" };
If I have detailed exceptions enabled, the 'error' argument on the client is 'Invalid login details' - the Message property of the exception.
Is there any way I can selectively change the error result from a string to a complex object? i.e. if 'CustomException' is thrown in a hub method, return a {Code:[...], Message:[...]} object for the client-side fail handler?
This should demonstrate what I'd like to see on the client:
hub.server.login(username, password).then(function(userInfo) {
alert("Hello " + userInfo.Name);
}, function(err) {
if (err.Code === "BADLOGIN.USERNAME")
alert("Unrecognised user name");
else if (err.Code === "BADLOGIN.PASSWORD");
alert("Invalid password");
else
alert("Unknown error: " + err.Message);
});
(Note the 'Code' and 'Message' properties on 'err').
When you call MapHubs with EnabledDetailedErrors set to true as follows:
RouteTable.Routes.MapHubs(new HubConfiguration { EnableDetailedErrors = true });
you will receive your Exception's Message string as the parameter to your fail handler.
I see that you have already figured this out, but I'm including the server side code to enable detailed errors for anyone else who might find this question later.
Unfortunately there is no easy way to send a complex object to the fail handler.
You could do something like this though:
if (!IsValidUsername(username))
{
var customEx = new CustomException { Code: "BADLOGIN.USERNAME", Message: "Invalid login details" };
throw new Exception(JsonConvert.SerializeObject(customEx));
}
if (!IsValidPassword(username, password))
{
var customEx = new CustomException { Code: "BADLOGIN.PASSWORD", Message: "Invalid login details" };
throw new Exception(JsonConvert.SerializeObject(customEx));
}
Then on the client:
hub.server.login(username, password).then(function(userInfo) {
alert("Hello " + userInfo.Name);
}, function(errJson) {
var err = JSON.parse(errJson);
if (err.Code === "BADLOGIN.USERNAME")
alert("Unrecognised user name");
else if (err.Code === "BADLOGIN.PASSWORD");
alert("Invalid password");
else
alert("Unknown error: " + err.Message);
});
I know this is ugly, but it should work.