Safe Resource Not Found (404) Exception Handling in ADO.net Data Service Client

There are many situations where you may encounter an undesired 404 “Resource Not Found” exception while querying against an ADO.net Data Service. For example, you may be writing a Linq query where the filter criteria is specified at runtime by the end users. When your query becomes input sensitive, there is no guarantee that the resource you are querying for exists on the server. In such situations, you may want your application to just ignore the exception thrown by the web request. In fact, when what you are looking for is not there, you probably expect an empty set rather than a big 404 on your screen.

As of V1.5, Astoria’s client can be set to silently “eat” the 404 exception, and just give back an empty collection. The switch is on the DataServiceContext itself, and it’s called “IgnoreResourceNotFoundException” (pretty self-explanatory name). When set to true, the client library will not longer throw DataServiceClientException when the server returns status code 404.

Consider the following example, where in a WinForm application, the user is allowed to query against the northwind database sitting at a remote service end point. The user can input any string in a textBox and that’ll be the CustomerID he’s looking for. You can now write:

context.IgnoreResourceNotFoundException = true;

var q = from c in context.CreateQuery<Customers>
        ("Customers")
where c.CustomerID == textBox1.Text
select c;

Customers cust = q.FirstOrDefault();
if (cust != null)
{
textBox2.Text = cust.CompanyName;
}
else
{
MessageBox.Show("The specified customer cannot be found");
}

Be careful when you are setting this property, since sometimes (especially during development) this can make your code harder to debug. A simple typo on the entity set name, for example, also causes 404 exceptions, and having IgnoreResourceNotFoundException turned on may just trick you into thinking the problem is elsewhere.