Implement DataNotFound exception in fetch

Implement DataNotFound exception in fetch

Old forum URL: forums.lhotka.net/forums/t/10589.aspx


kristof posted on Thursday, August 04, 2011

hi,

As was discussed previously (http://forums.lhotka.net/forums/t/10579.aspx) it is recommended to implement a "DataNotFoundException" in case you want to make sure a fetch always results in a valid object, even when the requested instance doesn't exist.

But, I am not sure how to make this work, given the fact that I call the DataPortal_Fetch method from a static factory method, while the referred to fetch method itself is a non-static instance method. I suspect it runs in a different context, making it impossible to catch any errors within the original factory method.

My code:

        public static Address GetAddress(...)
        {
            Address result = null;

            try
            {
                result = Csla.DataPortal.Fetch<Address>(crit);
            }
            catch (Exceptions.DataNotFoundException)
            {
                result = Address.GetNewAddress(connection, addressId);
            }

            return result;
        }

And:

            if (source.HasRows)
            {
        ...
            }
            else
            {
                throw new Exceptions.DataNotFoundException();
            }

I would think this would fall back to the previous catch block, but instead it just stops directly on the throw, as if the try catch didn't even exist. Which makes me suspect it runs in a totally different thread/context.

How do I fix this? Thx.

JonnyBee replied on Thursday, August 04, 2011

A: DataNotFoundException must be markes as [Serializable]

B: semantic of fetch should be

        public static Address GetAddress(...)
        {
            try
            {
                return Csla.DataPortal.Fetch<Address>(crit);
            }
            catch (DataPortalException ex)
            {

               if (ex.BusinessException is Exceptions.DataNotFoundException)
                   return Address.GetNewAddress(connection, addressId);
               else throw;
            }
        }

kristof replied on Thursday, August 04, 2011

That seems to have fixed it, thanks!

Copyright (c) Marimer LLC