简体   繁体   English

捕获在异步Web服务中完成的事件处理程序中引发的异常

[英]Catching exceptions thrown in an asynchronous web service completed event handler

Imagine a web service with a method that returns a Customer object, that takes a customer ID as a parameter, ie 想象一下一个Web服务,它具有一个返回Customer对象的方法,该方法将一个Customer ID作为参数,即

[WebMethod]
Customer GetCustomer(string customerId)

Now imagine that you're writing an ASP.NET app and you've generated a proxy for the service with the async operations. 现在,假设您正在编写一个ASP.NET应用程序,并且已经使用异步操作为该服务生成了代理。 You create an instance of the service, wire service.GetCustomerCompleted to your handler, OnGetCustomerCompleted, and call service.GetCustomerAsync("12345"). 创建服务的一个实例,将service.GetCustomerCompleted连接到处理程序OnGetCustomerCompleted,然后调用service.GetCustomerAsync(“ 12345”)。

In OnGetCustomerCompleted you apply logic to detect that no customer was found and throw a custom exception, or you want to throw the exception found in e.Error, eg: 在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();
}

(I've omitted the bits of code that sets up a Customer object and persists it through the calls.) (我省略了设置Customer对象并通过调用持久化的代码段。)

You launch the call to GetCustomerAsync in Page_Load and expect to retrieve the result in a handler wired to Page.OnPreRenderComplete. 您在Page_Load中启动对GetCustomerAsync的调用,并期望在连接到Page.OnPreRenderComplete的处理程序中检索结果。

My question is, how do you catch the exception in your page? 我的问题是,如何在页面中捕获异常? I know you can catch it with Global.asax's ApplicationError, but what if you don't want to navigate away from your page? 我知道您可以使用Global.asax的ApplicationError来捕获它,但是如果您不想离开页面怎么办?

You don't want to throw an exception from an event handler. 您不想从事件处理程序中引发异常。 There's nothing to catch the exception! 没有什么可以捕捉到异常的!

If you see an exception, set a flag in the page. 如果看到异常,请在页面中设置一个标志。 If you need your OnPreRenderComplete handler to use the exception details, the the flag can be the exception itself. 如果需要OnPreRenderComplete处理程序使用异常详细信息,则标志可以是异常本身。 If set to null, there was no exception, otherwise it is the exception that you found. 如果设置为null,则没有异常,否则就是您发现的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM