I have the following function that downloads a web page:
static bool myFunction(int nmsTimeout, out string strOutErrDesc)
{
//'nmsTimeout' = timeout in ms for connection
//'strOutErrDesc' = receives error description as string
bool bRes = false;
strOutErrDesc = "";
HttpClient httpClient = null;
System.Threading.Tasks.Task<string> tsk = null;
try
{
httpClient = new HttpClient();
tsk = httpClient.GetStringAsync("https://website-to-connet.com");
if (tsk.Wait(nmsTimeout))
{
if (tsk.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
{
string strRes = tsk.Result;
strRes = strRes.Trim();
if (!string.IsNullOrWhiteSpace(strRes))
{
bRes = true;
}
else
{
//Empty result
strOutErrDesc = "Empty result";
}
}
else
{
//Bad task completion
strOutErrDesc = "Bad completion result: " + tsk.Status.ToString();
}
}
else
{
//Timed out
strOutErrDesc = "Timeout expired: " + nmsTimeout + " ms.";
}
}
catch (Exception ex)
{
//Error
strOutErrDesc = "Exception: " + ex.Message;
if (tsk != null)
{
strOutErrDesc += " -- ";
int c = 1;
foreach(var exc in tsk.Exception.InnerExceptions)
{
strOutErrDesc += c.ToString() + ". " + exc.InnerException.Message;
}
}
bRes = false;
}
return bRes;
}
I thought that my try
/catch
construct was enough to catch all exceptions in it.
Until I found the following exception and the Windows error message that the app crashed:
Unhandled Exception: System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 503 (Service Unavailable).
--- End of inner exception stack trace ---
at System.Threading.Tasks.TaskExceptionHolder.Finalize()
What is this and how do I catch it?