views:

424

answers:

1

Imagine a web service with a method that returns a Customer object, that takes a customer ID as a parameter, i.e.

[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, e.g.:

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?

+1  A: 

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.

John Saunders
Ah, yes. Or if the async call is in a class called by the page (as my app really is structured) pass the exception out in the Customer object in a property or an object that has the Customer and exception as properties.
James McLachlan