I don't understand why but I'm receiving Flurl Exceptions and those are not being caught by the try/catch block. Any ideas on why that's happening?
Here's the code:
try
{
var x = await Utils.Sales.GetUrl()
.PostJsonAsync(new Sale
{
MerchantId = Constants.Sandbox.MerchantId
})
.ReceiveJson<Sale>();
var b = x;
}
catch (FlurlHttpTimeoutException)
{
//LogError("Timed out!"); //todo:
}
catch (FlurlHttpException ex)
{
var x = ex.Message;
//todo:
//if (ex.Call.Response != null)
// LogError("Failed with response code " + call.Response.StatusCode);
//else
// LogError("Totally failed before getting a response! " + ex.Message);
}
catch (Exception ex)
{
var a = ex.Message;
}
Here's the output (the only reason why I know the exception is being thrown):
Maybe this page will help https://msdn.microsoft.com/zh-cn/library/jj619227.aspx
Sorry don't have a english version, you can try google translate it.
It's someting wrong with you catch exception type or await code.
Try this way catch your exception:
```
try
{
await t1;
}
catch (AggregateException ex)
{
var innerEx = ex.InnerExceptions[0];
if (innerEx is NotSupportedException)
{
...
}
else if (innerEx is NotImplementedException)
{
...
}
else
{
...
}
}
```
Related
I'm new here and I hope you can help me with a problem I've got.
I'm trying to call some API's from Unity UWP, but every time on the third call I've got an Task Cancellation Exception, no matter what the order is of calling the api's.
Here is my piece of code:
public class DashboardManager : MonoBehaviour
{
public TMP_Text Status;
async Task Awake()
{
await GetPerformanceInfo().ConfigureAwait(false);
await GetProductionInfo().ConfigureAwait(false);
await GetChecklistInfo().ConfigureAwait(false);
}
private async Task GetChecklistInfo()
{
try
{
HttpClient httpClient = new HttpClient((HttpMessageHandler)ApiHelpers.HttpClientHandler);
httpClient.BaseAddress = new Uri(ApiHelpers.PlantApiBaseAddress.CheckBaseUrl(true));
var plantApiClient = new PlantApiClient(httpClient, default); // await ProgramManager.ServiceProvider.GetService<PlantApiClient>()
var checklists = await plantApiClient.GetChecklistWidgetInfo(UserSettings.Location);
//Status.text = "Checklist OK";
}
catch (LogoutException ex)
{
SceneManager.LoadScene("LoginScene");
}
catch (TaskCanceledException ex)
{
Status.text = "Checklist: " + ex.Message;
}
catch (Exception ex)
{
Status.text = "Checklist: " + ex.Message;
}
}
public void OnClickButton(string guid)
{
GlobalManager.CurrentChecklistID = guid;
SceneManager.LoadScene("ChecklistsScene");
}
private async Task GetPerformanceInfo()
{
try
{
HttpClient httpClient = new HttpClient((HttpMessageHandler)ApiHelpers.HttpClientHandler);
httpClient.BaseAddress = new Uri(ApiHelpers.PlantApiBaseAddress.CheckBaseUrl(true));
var plantApiClient = new PlantApiClient(httpClient, default); // await ProgramManager.ServiceProvider.GetService<PlantApiClient>()
var perfInfo = await plantApiClient.GetPerformanceWidgetInfo(UserSettings.Location);
//Status.text = "Performance OK";
}
catch (LogoutException ex)
{
SceneManager.LoadScene("LoginScene");
}
catch (TaskCanceledException ex)
{
Status.text = "Performance: " + ex.Message;
}
catch (Exception ex)
{
Status.text = "Performance: " + ex.Message;
}
}
private async Task GetProductionInfo()
{
try
{
HttpClient httpClient = new HttpClient((HttpMessageHandler)ApiHelpers.HttpClientHandler);
httpClient.BaseAddress = new Uri(ApiHelpers.PlantApiBaseAddress.CheckBaseUrl(true));
var plantApiClient = new PlantApiClient(httpClient, default); // await ProgramManager.ServiceProvider.GetService<PlantApiClient>()
var prodInfo = await plantApiClient.GetProductionWidgetInfo(UserSettings.Location);
//Status.text = "Production OK";
}
catch (LogoutException ex)
{
SceneManager.LoadScene("LoginScene");
}
catch (TaskCanceledException ex)
{
Status.text = "Production: " + ex.Message;
}
catch (Exception ex)
{
Status.text = "Production: " + ex.Message;
}
}
}
In the Awake Task, the 3rd call always fails with an TaskCancellation Exception.
If I change the order, it always fails on the third call.
There is nothing wrong with the api calls, because they are working as expected. If I just call one or two, everything works fine, but when I call a 3rd one, it fails.
What's happening here, I hope somebody can help me.
Damn, this took me 2 wasted days, just to figure out this was a bug in Unity 2020.3.11f1.
I installed version 2021.2.8f1 and everything is working fine now.
why does the try fail and the catch doesn't go where I can click on the next page to find the fleet?
Code:
try
{
if (!_regRep.btnNext.Displayed && !_regRep.btnNext.Enabled)
{
_fleetRep.btnDelete(Fleetname).Click();
}
}
catch
{
if (_regRep.btnNext.Displayed && _regRep.btnNext.Enabled)
{
objCommon.Click(_regRep.btnNext);
_fleetRep.btnDelete(Fleetname).Click();
}
}
Ok solved guys a lot more cleaner:
try
{
if (_regRep.btnNext.Displayed && _regRep.btnNext.Enabled)
{
objCommon.Click(_regRep.btnNext);
_fleetRep.btnDelete(Fleetname).Click();
}
}
catch (Exception ex)
{
_fleetRep.btnDelete(Fleetname).Click();
Console.WriteLine("No delete found: " + ex.Message);
}
How can I make ex accessible after a try catch block?
Like this...
try
{
// do something...
}
catch (Exception ex) {
// skip here...
}
//execute **ex** here
Why do I want to do this?
If I write:
try
{
// do something...
// i already declared x as public.
x = "what ever";
}
catch (Exception ex) {
// if there's an error...
Console.WriteLine(ex);
}
// Even there's an error,
// there's still no output.
So maybe if ex is public, I can try this:
try
{
// do something...
}
catch (Exception ex) {
// skip here...
}
// execute **ex** here
I am not sure what you mean with "execute ex", but this is how you could access the Exception after the catch block:
Exception ex = null;
try
{
// do something...
}
catch (Exception ex1) {
ex = ex1;
}
if(ex != null)
// ...
Exception exceptionObject = null;
try
{
// do something...
}
catch (Exception ex) {
exceptionObject = ex;
}
// execute **ex** here
if(exceptionObject != null)
{
//do a thing
}
The thing you are doing is weird. Stop it.
Basically, what I want to do is pass a specific Exception to a more general Exception within the same try block. I've tried the following and it doesn't work:
static bool example(int count = 0)
{
try
{
work();
}
catch (TimeoutException e)
{
if (count < 3)
{
Console.WriteLine("Caught TimeoutException: {0}", e.Message);
return example(count + 1);
}
else
{
throw new Exception(e.Message);
}
}
catch (Exception e)
{
Console.WriteLine("Caught Exception: {0}", e.Message + " rethrown");
return false;
}
return true;
}
static void work()
{
throw new TimeoutException("test");
}
I want the TimeoutException to be only handled a certain amount of times before going to a more generic Exception. This is because the TimeoutException has additional information about the exception on a case by case basis. I do not want to duplicate the code for Exception under the else clause of TimeoutException. The reason I want all exceptions to be handled is that there may be other unknown exceptions that are thrown. The nature of the program requires it to not crash so I must account for any other exceptions and log them. How can I implement this?
You would need to nest this as 2 tries if you want to handle this this way:
static bool example(int count = 0)
{
try
{
try
{
work();
}
catch (TimeoutException e)
{
if (count < 3)
{
Console.WriteLine("Caught TimeoutException: {0}", e.Message);
return example(count + 1);
}
else
{
// Just throw, don't make a new exception
throw; // new Exception(e.Message);
}
}
}
catch (Exception e)
{
Console.WriteLine("Caught Exception: {0}", e.Message + " rethrown");
return false;
}
return true;
}
The "inner try/catch" will only catch TimeoutException, so any other exception will always go to the outer scope. When you rethrow, it'll automatically get caught by the outer scope, as well, which eliminates the need for killing the exception information. (If you throw new Exception, you lose your stack trace data, and other very valuable debugging information.)
Here's my take:
bool example()
{
// Attempt the operation a maximum of three times.
for (int i = 0; i < 3; i++)
{
try
{
work();
return true;
}
catch (Exception e)
{
Console.WriteLine("Caught exception {0}", e.Message);
// Fail immediately if this isn't a TimeoutException.
if (!(e is TimeoutException))
return false;
}
}
return false;
}
EDIT
If you want to actually do something with the TimeoutException, you could change the catch block like so:
catch (Exception e)
{
// As Reed pointed out, you can move this into the if block if you want
// different messages for the two cases.
Console.WriteLine("Caught exception {0}", e.Message);
TimeoutException timeoutException = e as TimeoutException;
if (timeoutException != null)
{
// Do stuff with timeout info...
}
else
{
// Not a timeout error, fail immediately
return false;
}
}
Is it possible to return a bool and also rethrow an exception within the same method? Ive tried with the following code and it keeps saying that unreachable code is detected or that i cant exit the finally block.
public bool AccessToFile(string filePath)
{
FileStream source = null;
try
{
source = File.OpenRead(filePath);
source.Close();
return true;
}
catch (UnauthorizedAccessException e)
{
string unAuthorizedStatus = "User does not have sufficient access privileges to open the file: \n\r" + filePath;
unAuthorizedStatus += e.Message;
MessageBox.Show(unAuthorizedStatus, "Error Message:");
throw;
}
catch (Exception e)
{
string generalStatus = null;
if (filePath == null)
{
generalStatus = "General error: \n\r";
}
else
{
generalStatus = filePath + " failed. \n\r";
generalStatus += e.Message;
}
MessageBox.Show(generalStatus, "Error Message:");
throw;
}
finally
{
if (source != null)
{
source.Dispose();
}
}
}
Once you throw an exception, processing in your current method finishes and the exception works up the call stack. Either handle your exceptions locally and then return your boolean, or throw them and let them bubble up and handle them at the front end.