简体   繁体   中英

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

[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. You create an instance of the service, wire service.GetCustomerCompleted to your handler, OnGetCustomerCompleted, and call 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:

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.)

You launch the call to GetCustomerAsync in Page_Load and expect to retrieve the result in a handler wired to 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?

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. If set to null, there was no exception, otherwise it is the exception that you found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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