【发布时间】:2011-08-31 18:00:45
【问题描述】:
我有一个将 DateTime 作为参数的 Web 服务。如果用户传递的值格式不正确,.NET 会在它进入我的服务函数之前引发异常,因此我无法为客户端格式化一些好的 XML 错误响应。
例如:
[WebGet]
public IEnumerable<Statistics> GetStats(DateTime startDate)
{
//.NET throws exception before I get here
Statistician stats = new Statistician();
return ServiceHelper.WebServiceWrapper(startDate, stats.GetCompanyStatistics);
}
我现在的工作(我非常不喜欢)是:
[WebGet]
public IEnumerable<Statistics> GetStats(string startDate)
{
try
{
DateTime date = Convert.ToDateTime(startDat);
}
catch
{
throw new WebFaultException<Result>(new Result() { Title = "Error",
Description = "startDate is not of a valid Date format" },
System.Net.HttpStatusCode.BadRequest);
}
Statistician stats = new Statistician();
return ServiceHelper.WebServiceWrapper(startDate, stats.GetCompanyStatistics);
}
我在这里缺少什么吗?似乎应该有一种更清洁的方式来做到这一点。
【问题讨论】:
-
我不会使用空的
catch。仅捕获表示日期格式无效的异常。