如果你想分享更多的指针,你可以在这里找到整个源代码:
基本上我的API将为其他开发人员提供一种从http://www.dreamincode.net访问信息的简单方法- 在我的库中的一个方法中,我编写了这段代码:
public UserProfile FindUserById(int id)
{
if (id <= 0)
throw new ArgumentOutOfRangeException("id", id, "The user ID must be greater than 0.");
string xmlEndPoint = string.Format("http://www.dreamincode.net/forums/xml.php?showuser={0}", id.ToString());
string xmlResponse;
using (WebClient client = new WebClient())
{
try
{
xmlResponse = client.DownloadString(xmlEndPoint);
}
catch (Exception e)
{
throw new Exception("Error: " + e.InnerException);
}
}
if (String.IsNullOrEmpty(xmlResponse))
throw new Exception("Error: The XML endpoint did not respond.");
return UserParser.ParseUser(xmlResponse);
}
Run Code Online (Sandbox Code Playgroud)
我是否以最好的方式对待其他用户?.InnerException是否足以让其他开发人员知道出了什么问题?
感谢您的时间.:)
编辑:
所以按照你的建议,我写道:
using (WebClient client = new WebClient())
{
try
{
xmlResponse = client.DownloadString(xmlEndPoint);
}
catch (Exception e)
{
throw new Exception("Error: Something went wrong, please check the InnerException.", e);
}
}
Run Code Online (Sandbox Code Playgroud)
这是要走的路吗?这是保留堆栈跟踪吗?我做得对吗?
编辑2:
那么这是理想的解决方案吗?
//Just let it explode?
using (WebClient client = new WebClient())
{
xmlResponse = client.DownloadString(xmlEndPoint);
}
Run Code Online (Sandbox Code Playgroud)
不要扔Exception.相反,抛出适当的派生类型.
除非您有其他详细信息要提供,否则不要包含异常(throw来自a catch).
(例如它失败的页面,或者你认为它失败的原因)
包装异常时,始终将原始异常作为InnerException构造函数参数传递.这提供了对原始堆栈跟踪以及异常中的任何其他信息的访问.