Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return error from async funtion returning Task<T>

Tags:

c#

async-await

I have a basic asynchronous method in one class, which returns an object.

In some of the flows it may fail and I want to report it back.

But I can only return the object.

I tried nullable object, but got the error:

MyObject must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

I assume I can use exception, but I wanted something simpler in the calling function.

I also cannot use ref or out in async methods.

Is there a way to report back some kind of true/false of success or failure?

public static async Task<MyObject> getObject()
{
    if (NotOkFromSomeReason())
    {
          //Not sure what to do here
    }
    return await myDataBase.FindAsync(something);
}

I call it using:

  MyObject object = await getObject();
  // I want something simple as if(object)...
like image 324
Igal S. Avatar asked Mar 14 '16 11:03

Igal S.


2 Answers

Just wrap it into yet another class that will return both desired instance & status code - like:

public class StatusReport
{
    public boolean Ok { get; set; }
    public MyObject Instance { get; set; }
}

public static async Task<StatusReport> getObject()
{
  if (NotOkForSomeReason())
  {
    return new StatusReport { Ok = false };
  }
  return new StatusReport { Ok = true, Instance = await myDataBase.FindAsync(something) };
}
like image 126
Ondrej Svejdar Avatar answered Oct 30 '22 07:10

Ondrej Svejdar


If returning null is an option, you can do:

public static Task<MyObject> getObject()
{
  if (NotOkFromSomeReason())
  {
    return Task.FromResult<MyObject>(null);
  }
  return myDataBase.FindAsync(something);
}

PS: I'm supposing there's no other code which uses await in this function, so I've removed async. Otherwise you can just use the async qualifier and return null directly. Since it's returning Task objects, it's still awaitable from the outside

Then you could check for null outside:

MyObject myObject = await getObject();
if(myObject == null)
{
}

This will only work if null is not a possible "correct" result

You could otherwise use exceptions

like image 27
Jcl Avatar answered Oct 30 '22 07:10

Jcl