【发布时间】:2010-02-12 03:15:57
【问题描述】:
想象一个 Web 服务,其方法返回一个客户对象,该对象将客户 ID 作为参数,即
[WebMethod]
Customer GetCustomer(string customerId)
现在假设您正在编写一个 ASP.NET 应用程序,并且您已经为具有异步操作的服务生成了一个代理。您创建服务实例,将 service.GetCustomerCompleted 连接到您的处理程序 OnGetCustomerCompleted,然后调用 service.GetCustomerAsync("12345")。
在 OnGetCustomerCompleted 中应用逻辑来检测未找到客户并抛出自定义异常,或者您想抛出在 e.Error 中发现的异常,例如:
void OnGetCustomerCompleted(object sender, GetCustomerCompletedEventArgs e)
{
if (e.Error != null)
throw new ApplicationException("GetCustomer failed", e.Error);
if (String.IsNullOrEmpty(e.Result.FirstName) && String.IsNullOrEmpty(e.Result.LastName))
throw new CustomerNotFoundException();
}
(我省略了设置 Customer 对象并通过调用将其持久化的代码。)
您在 Page_Load 中启动对 GetCustomerAsync 的调用,并期望在连接到 Page.OnPreRenderComplete 的处理程序中检索结果。
我的问题是,如何在页面中捕获异常?我知道您可以使用 Global.asax 的 ApplicationError 捕获它,但是如果您不想离开您的页面怎么办?
【问题讨论】:
标签: c# asp.net exception-handling asynchronous