i have these class
//Class 1, ViewModel
public async System.Threading.Tasks.Task<JObject> ExecuteSystemObject(string parameters)
{
...
dynamic j = await ExternalProject.ExecuteSomething<MyModel>(parameters);
//How i can catch the error from the another class?
...
}
//Class2, Manager
public async Task<Object> ExecuteSomething<T>() where T : IModel, new()
{
...
WebResponse response = await ExternalProject.ExecuteRequestAsync(PostRequest);
...
}
//Class 3, from a binding Project
public static async Task<WebResponse> ExecuteRequestAsync(WebRequest request)
{
try
{
return await request.GetResponseAsync();
}
catch(WebException e)
{
var resp = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject(resp);
//I have the message error here
var messageFromServer = obj.error.text;
throw e;
}
}
I can get the error only in the last class, if i try to get the WebException in the other, it will return null for me. Then, how can i pass that error to the main class(1º one, ViewModel)?
Always use throw;
whenever you want to rethrow an exception for you to be able to retain the stacktrace.
public async System.Threading.Tasks.Task<JObject> ExecuteSystemObject(string parameters)
{
try
{
dynamic j = await ExternalProject.ExecuteSomething<MyModel>(parameters);
//How i can catch the error from the another class?
...
}
catch(Exception e)
{
//WebException will be caught here
}
}
public async Task<Object> ExecuteSomething<T>() where T : IModel, new()
{
try
{
WebResponse response = await ExternalProject.ExecuteRequestAsync(PostRequest);
}
catch(Exception)
{
throw;
}
}
public static async Task<WebResponse> ExecuteRequestAsync(WebRequest request)
{
try
{
//return await request.GetResponseAsync();
throw new WebException("Test error message");
}
catch(WebException e)
{
throw;
}
}
EDIT: Just a rule of thumb, only catch exceptions when you have something to do with it. If you are catching exceptions just to log it. Don't do it.