functional-csharp-code icon indicating copy to clipboard operation
functional-csharp-code copied to clipboard

Using the Exceptional with function returning Task<List<T>>

Open mookeyGit opened this issue 5 years ago • 2 comments

Hello, I am trying to use the Exceptional class in a function which queries the database and returns a Task<List<T>>. I am having a hard time understanding how to catch DB exceptions and return Exceptional within this function.

Here is the function:

public static Task<List<T>> ExecuteStoredProcedureAsync<T>(this ConnectionString connectionString, Some<string> spName, Some<object> spParamObj)
        {
            using SqlConnection connection = new SqlConnection(connectionString);
            var list = connection.QueryAsync<T>(spName, spParamObj.Value, commandType: CommandType.StoredProcedure).Result ?? new List<T>();

            return Task.FromResult(list.ToList());
        }

I started to add exception handling with the Exception class, like so:

public static Task<Exceptional<List<T>>> ExecuteStoredProcedureAsync_TEST<T>(this ConnectionString connectionString, Some<string> spName, Some<object> spParamObj)
        {
            try
            {
                using SqlConnection connection = new SqlConnection(connectionString);
                var list = connection.QueryAsync<T>(spName, spParamObj.Value, commandType: CommandType.StoredProcedure).Result ?? new List<T>();

                return Task.FromResult(F.Exceptional<List<T>>(list.ToList()));

            }
            catch (Exception ex)
            {
                return ex;
            }
        }

But, this obviously cannot work as the return type in the exception block needs to be compatible with the function's return type. I was under the assumption that the Exceptional class will convert to the appropriate type, but this seems to not be the case.

Can anyone help point me in the right direction. Thank you for your time.

mookeyGit avatar Jun 23 '20 21:06 mookeyGit

Task already encompasses failure, so the combination of Task and Exceptional is redundant

la-yumba avatar Jun 23 '20 22:06 la-yumba

Okay, yes, I didn't think of that. Thank you for your help—much appreciated!

mookeyGit avatar Jun 23 '20 22:06 mookeyGit