How to throw exception with MessageBox in Xamarin - xamarin

I'm make an app which get data from API, but sometimes error will occur.
I have throw exception in my code when StatusCode is not Ok. But i have to handle it.
So, my question is how to get the exception on another thread and throw it with message box in xamarin.
ProductsNew = await Task.Run(() =>
{
ProductViewData productNewViewData = new ProductViewData();
return productNewViewData.GetProductNew("5");
});
Thanks for any help.

Put your code in try and catch block and show the error on message box.
try
{
//code
}
catch(Exception ex)
{
DisplayAlert("Error",ex.Message,"Ok");
}

Related

Laravel package whoops exception

In my Laravel package I have this code:
try {
$var_msg = "Exception example";
throw new InvalidNameException($var_msg);
}
catch (InvalidNameException $e) {
abort(403, $e->getMessage());
//report($e);Exception Log
}
The error is displayed as html error page. But, I'd like to report the error as an whoops error.
Take this code as reference.
$whoops = new \Whoops\Run();
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler());
// Set Whoops as the default error and exception handler used by PHP:
$whoops->register();
throw new \RuntimeException("Oopsie!");

Unable to catch error in laravel using try catch

I wrote a code to try and catch error.
I want that if the error occurs then laravel continues to the next one and i write the error in the error file as shown here.
Laravel's black page of error pops up which shows "ErrorException (E_WARNING) followed by the whole error on the left page and the programme is abruptly stopped.
Is there a way to skip the error notification which brings my whole code to a stop.
My attempt at coding to catch the error is here:
try {
$jsondata_car = (file_get_contents($urltofind_car));
} catch (Exception $e) {
$errorfile = fopen("errors", 'a');
fwrite($errorfile, $e - > getmessage().
"\n");
$failed_car = 9999999;
report($e);
return false;
}
Am I missing out something?
The error I get is here
file_get_contents(): failed to open stream:
HTTP request failed! HTTP/1.1 400 Bad Request
The error is shown on the line
$jsondata_car = (file_get_contents($urltofind_car));
The solution is here
Exception is used which should have contained a namespace.
The problem is that this does not throw up an error even though I had not written
Use Exception;
at the beginning.
As suggested by #simon R I made the rectification and it worked.
It is most likely still throwing the error because you haven't imported the Exception class
Ensure you either add
Use Exception;
to your class.
Alternative update your code to namespace it;
try {
$jsondata_car = (file_get_contents($urltofind_car));
} catch (\Exception $e) {
$errorfile = fopen("errors", 'a');
fwrite($errorfile, $e - > getmessage().
"\n");
$failed_car = 9999999;
report($e);
return false;
}

ManualResetEvent with HttpWebRequest on WP7

To start off with, this might be tagged as a duplicate of the following thread:
Wait for HttpWebRequest.BeginGetResponse to finish in Windows Phone 7, however, the responses in that thread did not help me get over my problem.
To begin with, I am collecting user data on the UI Thread in order to process application registration, where I also have an instance of ManualResetEvent:
private static ManualResetEvent registrationEvent = new ManualResetEvent(false);
I have another thread which handles the registration process (and includes the HttpWebRequest.BeginGetResponse() and its corresponding callback method.)
Thread t = new Thread(() => RegistrationHandler.sendRegistrationData(url));
t.Start();
Right after this call, I block the current (UI) thread with a call to
registrationEvent.WaitOne();
//Process the response, update some UI elements and navigate to a different page.
httpSessionCompleted(response);
Once the thread handling the registration process starts, I am instantiating HttpWebRequest and invoking the BeginGetResponse() method on it.
try
{
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "POST";
request.ContentType = mimeType;
request.BeginGetResponse(new AsyncCallback(GetRequestCallback), request);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in sendData(): {0}", ex.Message);
}
Now the issue is that the callback method (code below) is never invoked, and the application just freezes. There also doesn't seem to be any exception(s) thrown either.
try
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
if (request != null)
{
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
String result = reader.ReadToEnd();
Globals.HostResponse = result;
//Signalling the calling thread to continue execution
RegistrationPage.RegistrationEvent.Set();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in GetRequestCallback(): {0}", ex.Message);
}
I ideally want my application to continue from httpSessionCompleted() after the callback method finishes execution. Can someone please help me with some guidance/suggestions?
Sorry for being verbose. Thanks!
You should not block UI thread, use callback pattern instead. Look at this: Windows Phone 7 - wait for Webclient to complete . Hope this helps

OAuthException not catched with C# FacebookSDK

I try to get my code working with catching certain errors. I store the token for a user after he or she grants permission to my app (this is a WP7 app). When I try to post on the wall by using the stored token it works. When I remove the permissions on facebook it throws an OAuthException. I can't catch it it seems. My app just crashes. This is the code I used:
private object PostToFacebook()
{
_fbApp = new FacebookClient(_appsettings.faceBookToken);
FacebookAsyncCallback callback = new FacebookAsyncCallback(this.postResult);
var parameters = new Dictionary<string, object>();
parameters.Add("message", "message on wall");
try
{
_fbApp.PostAsync("me/feed", parameters, callback);
}
catch (Exception ex)
{
}
return null;
}
private void postResult(FacebookAsyncResult asyncResult)
{
if (asyncResult.Error == null)
{
status = "succes";
}
else
{
status = "error" + asyncResult.Error.Message;
}
}
The try catch doesn't catch anything and the generic exception handler in my app.xaml.cs either.
Any ideas how to catch this error so I can ask the user to authenticate again?
Put your try..catch in the callback.
You can also catch exceptions globally by handling the UnhandledException event on the App object.

NotSupportedException when adding entity via odata on windows phone

I'm using the odata client generator (DataSvcUtil.exe) in a Windows Phone 7 application. Retrieving entities and collections is fine as is updating an existing entity. But when I try to add a new entity, I get a NotSupportedException. Here's my code.
private void Button_Click(object sender, RoutedEventArgs e)
{
Drinks d =new Drink();
d.BarCode = "1234567890";
d.Description = "Test Drink";
d.Quantity = -1;
context.AddToDrinks(d);
context.BeginSaveChanges(SaveChangesOptions.Batch, OnChangesSaved, context);
}
private void OnChangesSaved(IAsyncResult result)
{
Dispatcher.BeginInvoke(() =>
{
try
{
var something = result.AsyncState;
context = result.AsyncState as DrinkTrackerModelContainer;
// Complete the save changes operation and display the response.
ShowSaveResponse("Drink Logged!", context.EndSaveChanges(result));
}
catch (DataServiceRequestException ex)
{
ShowSaveResponse("Error Logging Drink", ex.Response);
}
catch (InvalidOperationException ex)
{
ShowSaveResponse(ex.Message, null);
}
}
);
}
As soon as EndSaveChanges is called, I get the
NotSupportedException.
EDIT: I used fiddler and saw that I was in fact getting a different exception from the service. That exception data was not being shown in the debugger. Once I corrected the actual exception, the insert worked fine.
I think you have first chance exceptions turned on which is causing an internal exception thrown by the client library to surface as an exception. Try turning off First Chance Exceptions in the "Exceptions" menu in VS and running the app.
As you mentioned in your edit, the NotSupportedException was a red herring. I think that when debugging a phone app you will hit the NotSupportedException even if you have cleared the setting to break on unhandled CLR exceptions.
If you continue(F5), you'll hit an actual DataServiceRequestException exception. If it doesn't have enough information to debug it, you can follow the steps in this post to get more detailed information in the exception: http://blogs.msdn.com/b/phaniraj/archive/2008/06/18/debugging-ado-net-data-services.aspx
I ran into the same problem yesterday, and after following the steps in the blog I was able to successfully debug the problem.

Resources