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

Viewed 16028

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)...
2 Answers
Related