How would you correct way to handle an exception in this situation? Initially I expect that using a trycatch in the following manner would catch the exception thrown by the helper class when the upload fails.
My aim is for “false” to be returned and a Messagebox to open with the error message I’ll be plucking out of the HTML response from my upload attempt.
I am trying to do this without resorting to bad practise and putting GUI code inside my helper class.
try
{
// returns bool
successful = UploadHelper.Upload(uploadToPath, File.ReadAllBytes(uploadFromPath), properties);
}
catch (Exception ex)
{
string error = ex.Message;
}
Helper class:
public static bool Upload(string webUrl, string documentName, byte[] bytes, Dictionary<string, object> metaInfo, out string result)
{
try
{
using (WebClient webClient = new WebClient())
{
//result is HTML string containing data
result = Encoding.UTF8.GetString(webClient.UploadData(webUrl + "/_vti_bin/_vti_aut/author.dll", "POST", data.ToArray()));
// if fails throw exception
if (result.IndexOf("\n<p>message=successfully") < 0)
throw new Exception(result);
}
}
catch (Exception ex)
{
result = ex.Message;
// Upload failed
return false;
}
// Upload succeeded
return true;
}
This slightly similar question lead me to thinking I could resolve this issue with a custom exception. However reading this explanation of creating them has confused me as to how they could be used to resolve this situation – as it seems this would just move the Messagebox code to the Exception class which is also not a great place for it.
I am fairly sure this is a situation where I am justified in using a custom exception anyway as the user may be able to resolve the issues depending on the error message returned. So I have written from the aforementioned guide anyway (left out of code example for simplicity).
If you are just going to display the exception’s message in the UI, and your
catchblock here is just to grab the message, why catch it here at all? If the handling is in the UI, then catch it there (or closer to there) and just grab and display the message at that level.You’d generally use exception handling in this sort of case to either grab specific exceptions and extract information from them to report in a particular way (abstract the error message as Charleh comments below), or to drive some sort of automatic retry logic. But there’s absolutely nothing wrong with a method called
Uploadthrowing an exception if it fails to upload something.